예제 #1
0
def verify_phone():
    number = get_header("number")

    if (number):
        client = Client.get_from_number(number)

        if (client):
            return jsonify({"token": client.token})
        else:
            return jsonify({"token": Client.add(number).token})
    else:
        abort(400)
예제 #2
0
파일: client.py 프로젝트: cash2one/braavos
def new_client():
    form = NewClientForm(request.form)
    if request.method == 'POST' and form.validate():
        db_client_name = Client.name_exist(form.name.data)
        if not db_client_name:
            client = Client.add(form.name.data, form.industry.data)
            flash(u'新建客户(%s)成功!' % client.name, 'success')
        else:
            flash(u'客户%s已存在,不用添加!' % form.name.data, 'danger')
            return tpl('client.html', form=form, title=u"新建客户")
        return redirect(url_for("client.clients"))
    return tpl('client.html', form=form, title=u"新建客户")
예제 #3
0
def _into_order(param):
    group = Group.query.filter_by(name=u'默认集团').first()
    if not group:
        group = Group.add(name=u'默认集团')
        group.save()

    agent = Agent.query.filter_by(name=param['agent_name']).first()
    if not agent:
        agent = Agent.add(
            name=param['agent_name'],
            group=group,
            tax_num='',
            address='',
            phone_num='',
            bank='',
            bank_num='',
        )

    client = Client.query.filter_by(name=param['client_name']).first()
    if not client:
        client = Client.add(name=param['client_name'], industry=1)
        # client.save()

    medium = Medium.query.filter_by(name=param['medium_name']).first()
    if not medium:
        medium = Medium.add(name=param['medium_name'],
                            abbreviation=param['medium_name'],
                            tax_num='',
                            address='',
                            phone_num='',
                            bank='',
                            bank_num='',
                            owner=Team.query.filter_by(type=8).first())

    team_huabei = Team.query.filter_by(name=u'导入渠道销售团队华北').first()
    if not team_huabei:
        team_huabei = Team.add(
            name=u'导入渠道销售团队华北',
            type=4,
            location=1,
            admins=[],
        )

    team_huanan = Team.query.filter_by(name=u'导入渠道销售团队华南').first()
    if not team_huanan:
        team_huanan = Team.add(
            name=u'导入渠道销售团队华南',
            type=4,
            location=3,
            admins=[],
        )

    team_huadong = Team.query.filter_by(name=u'导入渠道销售团队华东').first()
    if not team_huadong:
        team_huadong = Team.add(
            name=u'导入渠道销售团队华东',
            type=4,
            location=2,
            admins=[],
        )

    team_qita = Team.query.filter_by(name=u'导入渠道销售团队其他').first()
    if not team_qita:
        team_qita = Team.add(
            name=u'导入渠道销售团队其他',
            type=4,
            location=0,
            admins=[],
        )

    if not param['agent_sale_name']:
        agents = []
    else:
        agent_names = param['agent_sale_name'].split(' ')
        agents = []
        if param['location'] == u'华北':
            team = team_huabei
        elif param['location'] == u'华东':
            team = team_huadong
        elif param['location'] == u'华南':
            team = team_huanan
        else:
            team = team_qita
        for k in agent_names:
            name = k.strip()
            p_name = p.get_pinyin(name, '').lower()
            email = p_name + '@inad.com'
            user = User.query.filter_by(email=email).first()
            if not user:
                user = User.add(name, email, 'pwd@inad', team, 1)
            agents.append(user.id)

    if param['contract_type'].find(u'非标') >= 0:
        contract_type = 1
    else:
        contract_type = 0

    if param['resource_type'].find(u'硬广') >= 0:
        resource_type = 0
    elif param['resource_type'].find(u'互动') >= 0:
        resource_type = 1
    else:
        resource_type = 4

    if param['sale_type'] == u'代理':
        sale_type = 0
    else:
        sale_type = 1

    if ClientOrder.query.filter_by(agent=agent,
                                   client=client,
                                   campaign=param['campaign'],
                                   status=1).first():
        return

    order = ClientOrder.add(
        agent=agent,
        client=client,
        campaign=param['campaign'],
        money=param['money'],
        client_start=param['medium_start'],
        client_end=param['medium_end'],
        reminde_date=param['reminde_date'],
        direct_sales=[],
        agent_sales=User.gets(agents),
        contract_type=contract_type,
        resource_type=resource_type,
        sale_type=sale_type,
        creator=g.user,
        create_time=datetime.datetime.now(),
    )
    order.add_comment(
        g.user, u"新建了客户订单:%s - %s - %s" %
        (order.agent.name, order.client.name, order.campaign))
    mo = Order.add(campaign=order.campaign,
                   medium=medium,
                   sale_money=param['money'],
                   medium_money=param['medium_money'],
                   medium_money2=param['medium_money2'],
                   medium_start=param['medium_start'],
                   medium_end=param['medium_end'],
                   creator=g.user)
    order.add_comment(g.user,
                      u"新建了媒体订单: %s %s元" % (medium.name, mo.sale_money))
    order.medium_orders = [mo]
    order.save()
    return
예제 #4
0
def first_run():
    from models.client import Client
    from models.category import Category
    from models.orders import Order
    from models.product import Product
    from models.restaurants import Restaurant
    from models.user import User
    meta = sqlalchemy.MetaData(engine)
    meta.reflect()
    #meta.drop_all()

    print("First run, please wait while the db is being populated...")

    # Create tables
    Base.metadata.create_all(engine)

    testClient = Client.add("6977988551")
    testClient2 = Client.add("8891155521")

    restaurant = Restaurant.add(
        "Restaurant 1",
        "The best food you'll find in the city\nWe make sandwiches, salads and burgers"
    )

    sandwichesCategory = Category.add("Sandwiches", restaurant)
    Product.add("Pulled Pork", "With tangy barbecue sauce on an onion knot",
                9.50, restaurant, sandwichesCategory)
    Product.add(
        "Turkey Club",
        "Roasted turkey breast, bacon, lettuce, avocado and tomato on baguette",
        8, restaurant, sandwichesCategory)
    Product.add(
        "Reuben",
        "Corned beef, melted swiss, sauerkraut and thousand island on marbled rye",
        8, restaurant, sandwichesCategory)
    Product.add(
        "Shrimp Cilantro Wrap",
        "Shrimp, avocado, mixed greens, salsa, cilantro and may on a tomato tortilla",
        8.5, restaurant, sandwichesCategory)

    burgerCategory = Category.add("Burgers", restaurant)
    Product.add(
        "Grass-fed Beef Burger",
        "With sharp cheddar, heirloom tomatoes and caramelized onions", 9.5,
        restaurant, burgerCategory)
    Product.add(
        "Mushroom Swiss Burger",
        "With sautéed mushrooms and melted swiss on a home-baked roll", 10,
        restaurant, burgerCategory)
    Product.add(
        "Hickory Burger",
        "Topped with cheddar, hickory smoked bacon and smoked barbecue sauce",
        10, restaurant, burgerCategory)
    Product.add(
        "Chicken Burger",
        "Grilled chicken breast with heirloom tomatoes, avocado and sprouts on a home-baked roll",
        9, restaurant, burgerCategory)

    saladCategory = Category.add("Salads", restaurant)
    Product.add(
        "Caesar Salad",
        "Romaine, fresh parmesan, seasoned croutons and black pepper with garlic anchovy dressing",
        6.75, restaurant, saladCategory)
    Product.add("Red Iceberg Salad",
                "With sweet corn, blackberries, goat cheese and fresh basil",
                9.25, restaurant, saladCategory)
    Product.add(
        "House Salad",
        "With green olives, green peppers, onions, cucumbers, and tomato",
        6.75, restaurant, saladCategory)
    Product.add(
        "Blue Chicken Salad",
        "Mesclun greens, apple, grilled chicken, gorgonzola, chesse and balsamic vinagrette",
        9.25, restaurant, saladCategory)

    # Add an user for the restaurant we just created
    User.add("restaurant1", "restaurant1", 0, restaurant)

    streets = [
        "Oak Street", "Madison Avenue", "Bridle Lane", "Jefferson Street",
        "Lafayette Avenue", "Grove Street", "Chestnut Avenue"
    ]

    # Simulate some orders on a different client
    originalDate = time.time() - 57600000
    for i in range(87):
        productCount = randint(1, 2)
        used = {}
        products = []
        price = 0

        originalDate += randint(376000, 576000)

        for y in range(productCount):
            id = randint(0, 11)
            while (id in used):
                id = randint(0, 11)

            used[id] = True
            amount = randint(1, 2)
            products.append({"id": id + 1, "count": amount})
            product = Product.get_from_id(id + 1)
            price += amount * product.price

        order = Order.add(
            random.choice(streets) + " " + str(randint(1, 5000)), price, "",
            products, [-34.601874, -58.432611], testClient2, restaurant)
        order.date = originalDate
        order.status = 2
        get_session().commit()

    Order.add("Bridle Lane 1775", 9.50, "", [{
        'id': 1,
        'count': 1
    }], [-34.601874, -58.432611], testClient, restaurant)
예제 #5
0
    def post(self):
        try:
            requestDict = request.get_json()
            if not requestDict:
                response = {'error': 'No input data provided'}
                return response, status.HTTP_400_BAD_REQUEST

            # Datos para la cuenta
            idPerson = requestDict['idPerson']

            #Datos para el prospecto
            email1 = requestDict['email1']
            email2 = requestDict['email2']
            cellphone1 = requestDict['cellphone1']
            cellphone2 = requestDict['cellphone2']
            lastEnterDate = datetime.now() - timedelta(hours=5)

            prospectiveClient = ProspectiveClient.query.filter_by(
                idPerson=idPerson).first()
            if not prospectiveClient:
                prospectiveClient = ProspectiveClient(
                    idPerson=idPerson,
                    email1=email1,
                    email2=email2,
                    cellphone1=cellphone1,
                    cellphone2=cellphone2,
                    lastEnterDate=lastEnterDate)
                prospectiveClient.enterCount = 1
                prospectiveClient.add(prospectiveClient)
            else:
                prospectiveClient.email1 = email1
                prospectiveClient.email2 = email2
                prospectiveClient.cellphone1 = cellphone1
                prospectiveClient.cellphone2 = cellphone2
                prospectiveClient.lastEnterDate = lastEnterDate
                prospectiveClient.enterCount += 1
                prospectiveClient.update()

            #Commit registro de prospecto
            db.session.commit()

            client = Client(registerDate=lastEnterDate,
                            totalAccounts=0,
                            activeLoans=0,
                            active=1,
                            idProspectiveClient=prospectiveClient.id)
            client.add(client)

            #Commit registro de cliente
            db.session.commit()

            resp = {'ok': 'Cliente registrado con exito.'}

            return resp, status.HTTP_201_CREATED
        except SQLAlchemyError as e:
            db.session.rollback()
            response = {'error': str(e)}
            return response, status.HTTP_400_BAD_REQUEST
        except Exception as e:
            db.session.rollback()
            response = {
                'error':
                'An error ocurred. Contact cat-support asap. ' + str(e)
            }
            return response, status.HTTP_400_BAD_REQUEST
예제 #6
0
    def post(self):
        requestDict = request.get_json()
        if not requestDict:
            response = {'error': 'No input data provided'}
            return response, status.HTTP_400_BAD_REQUEST
        curdatetime = datetime.now() - timedelta(hours=5)
        try:
            accountType = 1  #Cuenta Simple por defecto
            if 'accountType' in requestDict:
                accountType = int(requestDict['accountType'])
            idPerson = requestDict['idPerson']
            origin = requestDict['origin']
            prospectiveClient = ProspectiveClient.query.filter_by(
                idPerson=idPerson).first()
            client = Client.query.filter_by(
                idProspectiveClient=prospectiveClient.id).first()
            if not client:  #Apertura de cuentas no cliente
                client = Client(registerDate=curdatetime,
                                totalAccounts=1,
                                activeLoans=0,
                                active=1,
                                idProspectiveClient=prospectiveClient.id)
                client.add(client)
            else:
                client.totalAccounts += 1
                client.update()
            db.session.flush()
            orig = ""
            if origin == 1:
                orig = "Web"
            else:
                orig = "Ventanilla"
            salesRecord = SalesRecord(origin=orig,
                                      active=1,
                                      requestDate=curdatetime,
                                      idClient=client.id,
                                      idRecordStatus=1,
                                      idProduct=1)
            salesRecord.add(salesRecord)
            db.session.flush()
            currency = requestDict['currency']
            account = Account(accountNumber=GenerateAccount(),
                              balance=0.0,
                              openingDate=curdatetime,
                              closingDate=None,
                              cardNumber="1234-5678-1234-5678",
                              idAccountType=accountType,
                              idSalesRecord=salesRecord.id,
                              idCurrency=currency,
                              idClient=client.id,
                              active=1)
            account.add(account)
            db.session.flush()
            response1 = requestDict['response1']
            response2 = requestDict['response2']
            response3 = requestDict['response3']
            response4 = requestDict['response4']
            additionalQuestion = AdditionalQuestion(response1=response1,
                                                    response2=response2,
                                                    response3=response3,
                                                    response4=response4,
                                                    idAccount=account.id)
            additionalQuestion.add(additionalQuestion)

            #Commit changes
            db.session.commit()

            regClient = Client.query.get(client.id)
            regAccount = Account.query.get(account.id)
            regAccountType = AccountType.query.get(accountType)
            person = Person.query.get(prospectiveClient.idPerson)
            d = {}
            d['name'] = " ".join([
                person.firstName, person.middleName, person.fatherLastname,
                person.motherLastname
            ])
            d['accountNumber'] = regAccount.accountNumber
            d['cci'] = "0011-" + regAccount.accountNumber
            d['accountDetail'] = regAccountType.typeName
            d['openingDate'] = regAccount.openingDate.strftime('%d-%m-%Y')
            d['currency'] = ('Soles'
                             if regAccount.idCurrency == 1 else 'Dolares')
            d['email'] = prospectiveClient.email1

            from mailing import mail
            msg = Message("Tunke - Apertura de cuenta exitosa",
                          sender="*****@*****.**",
                          recipients=[d['email']])
            msg.body = 'Hola'
            msg.html = render_template('ejemplo.html',
                                       name=d['name'],
                                       accountNumber=d['accountNumber'],
                                       cci=d['cci'],
                                       accountDetail=d['accountDetail'],
                                       openingDate=d['openingDate'],
                                       currency=d['currency'])
            mail.send(msg)
            return d, status.HTTP_201_CREATED

        except SQLAlchemyError as e:
            db.session.rollback()
            response = {'error': str(e)}
            return response, status.HTTP_400_BAD_REQUEST
        except Exception as e:
            db.session.rollback()
            response = {
                'error':
                'An error ocurred. Contact cat-support asap. ' + str(e)
            }
            return response, status.HTTP_400_BAD_REQUEST
예제 #7
0
from app import app
from libs.db import db
db.create_all()

from models.user import (User, Team, TEAM_TYPE_SUPER_ADMIN, TEAM_TYPE_MEDIUM,
                         TEAM_TYPE_LEADER, TEAM_TYPE_DIRECT_SELLER)
from models.medium import Medium, MediumGroup
from models.client import Client, Agent, Group
from models.order import Order
from config import DEFAULT_PASSWORD

admin_team = Team.add(u'管理员', type=TEAM_TYPE_SUPER_ADMIN)
medium_team = Team.add(u'媒体', type=TEAM_TYPE_MEDIUM)
leader_team = Team.add('ledaer', type=TEAM_TYPE_LEADER)
sale_team = Team.add('ledaer', type=TEAM_TYPE_DIRECT_SELLER)


user = User.add(name="admin", email="*****@*****.**", password=DEFAULT_PASSWORD, team=admin_team)
leader = User.add(name="leader", email="*****@*****.**", password=DEFAULT_PASSWORD, team=leader_team)
saler = User.add(name="saler", email="*****@*****.**", password=DEFAULT_PASSWORD, team=sale_team)

medium_group = MediumGroup.add(name='测试媒体供应商', tax_num="", address="",
                               phone_num="", bank="", bank_num="", level=100)
medium = Medium.add(medium_group, u"测试媒体", owner=medium_team)

client = Client.add(u"测试客户", 0)

group = Group.add(u'测试代理集团')

agent = Agent.add(u"测试代理", group=group)
예제 #8
0
def add_client(name):
    client = Client.add(name, 0)
    return client
예제 #9
0
파일: fill_up.py 프로젝트: cash2one/braavos
leader_team = Team.add('ledaer', type=TEAM_TYPE_LEADER)
sale_team = Team.add('ledaer', type=TEAM_TYPE_DIRECT_SELLER)

user = User.add(name="admin",
                email="*****@*****.**",
                password=DEFAULT_PASSWORD,
                team=admin_team)
leader = User.add(name="leader",
                  email="*****@*****.**",
                  password=DEFAULT_PASSWORD,
                  team=leader_team)
saler = User.add(name="saler",
                 email="*****@*****.**",
                 password=DEFAULT_PASSWORD,
                 team=sale_team)

medium_group = MediumGroup.add(name='测试媒体供应商',
                               tax_num="",
                               address="",
                               phone_num="",
                               bank="",
                               bank_num="",
                               level=100)
medium = Medium.add(medium_group, u"测试媒体", owner=medium_team)

client = Client.add(u"测试客户", 0)

group = Group.add(u'测试代理集团')

agent = Agent.add(u"测试代理", group=group)