Beispiel #1
0
def api_contract_new(*, userid, contractid):
    'add contract'
    if not userid:
        raise APIValueError('userid')
    if not contractid:
        raise APIValueError('contractid')
    fromid = next_id()
    fcontract = Contract(id=fromid, userid=userid, contractid=contractid)
    fres = yield from fcontract.save()
    toid = next_id()
    tcontract = Contract(id=toid, userid=contractid, contractid=userid)
    tres = yield from tcontract.save()
    return {'fres': fres, 'tres': tres}
Beispiel #2
0
def createContract():
    """ Contract creation """
    try:
        if "username" in session:
            if request.method == 'POST':
                myContract = Contract(
                    contractref=request.form["inputContractReference"],
                    systemname=request.form["inputSystemName"],
                    contractrenewtype=request.form["inputRenewType"],
                    contractcost=request.form["inputContractCost"],
                    contractstartingdate=request.
                    form["inputContractStartingDate"],
                    contractendingdate=request.form["inputContractEndingDate"],
                    contractcomment=request.form["inputContractComment"],
                    contractyear=request.form.get("inputContractYear",
                                                  type=int))
                myContract.save()
                flash('Contract saved !!! ', 'message')
                return redirect(url_for('listeContract'))
            if request.method == 'GET':
                return render_template('createcontract.html')
        else:
            flash('Unknown user !!! ', 'error')
            return render_template('login.html')
    except:
        return redirect(url_for('appError'))
Beispiel #3
0
def contractAdd(request):
    user = request.user
    context = {"user": user}
    try:
        if request.method == 'POST':
            context['post'] = 'y'
            contract = Contract()
            contract.department = request.POST['institute']
            contract.user = user
            contract.personell_number = request.POST['personell_id']
            cStart = request.POST['contract_start']
            cEnd = request.POST['contract_end']
            cStart = datetime.strptime(cStart, "%Y-%m-%d")
            cEnd = datetime.strptime(cEnd, "%Y-%m-%d")
            contract.contract_begin = cStart
            contract.contract_end = cEnd
            contract.personell = request.POST['dp']
            contract.hours = request.POST['work_hours']
            contract.payment = request.POST['payment']
            contract.vacation = round((int(contract.hours) * 20 * 3.95) / 85.0)
            contract.clean_fields()
            contract.save()
            return redirect("/profile")

    except ValidationError as v:
        context['error'] = v.messages
        print(v)
    except ValueError as v:
        context['error'] = [v.message]
    context['postdata'] = request.POST
    return render(request, 'contract_add.html', context)
Beispiel #4
0
def add_contract():
    """добавление контракта"""

    agent_id = int(input('id агента: '))

    # проверка на правильнось введеного id агента
    agent_query = session.query(Agent).filter_by(id=agent_id).all()
    if agent_query:
        print(f'Выбран контрагент: {agent_query[0]}')
    else:
        print('Не вероно указан id агента...\n')
        return

    number = input('Номер договора: ')
    contract_query = session.query(Contract).filter_by(agent_id=agent_id,
                                                       number=number).all()
    if contract_query:
        print(
            f'У контрагента {agent_query[0]} уже есть договор {contract_query[0]}'
        )
        return

    description = input('Краткое описание договора: ')

    new_contract = Contract(agent_id=agent_id,
                            number=number,
                            description=description)
    session.add(new_contract)
    session.commit()
    print(f'Договор №{number} добавлен\n')
Beispiel #5
0
 def add_contract_to_actor():
     try:
         print("Input movie name:")
         movie_name = input()
         print("Input actor name:")
         actor_name = input()
         print("Input studio name:")
         studio_name = input()
         print("Input value:")
         value = int(input())
         if movie_name and actor_name and studio_name and value:
             s = Session()
             movie = s.query(Movie).filter_by(name=movie_name).first()
             studio = s.query(Studio).filter_by(name=studio_name).first()
             actor = s.query(Actor).filter_by(full_name=actor_name).first()
             if (movie is None) or (actor is None) or (studio is None):
                 View.display_no_results()
                 s.close()
             else:
                 s.add(
                     Contract(movie_id=movie.id,
                              studio_id=studio.id,
                              actor_id=actor.id,
                              value=value))
                 s.commit()
                 s.close()
                 View.display_success()
         else:
             print("Incorrect input")
     except SQLAlchemyError as e:
         View.display_error()
Beispiel #6
0
def product_add_contract():

    api_key = request.headers.get('Authorization')
    response = UserClient.get_user(api_key)

    if not response:
        return make_response(jsonify({'message': 'Not logged in'}), 401)

    user = response['result']
    if int(user['id']) == int(request.form['contractor_user_id']):
        return make_response(
            jsonify({'message': 'user can not sign contract with himself'}),
            401)
    contract_instance = Contract()
    contract_instance.title = request.form['title']
    contract_instance.content = request.form['content']
    contract_instance.user_id = int(user['id'])
    contract_instance.contractor_user_id = request.form['contractor_user_id']
    contract_instance.contract_template_id = request.form[
        'contract_template_id']
    contract_instance.value = request.form['value']
    contract_instance.duedate = request.form['duedate']

    db.session.add(contract_instance)
    db.session.commit()

    response = jsonify({'result': contract_instance.to_json()})

    return response
    def add(self, contract_id, clinic_id):
        contract = Contract.query.filter_by(id=contract_id).first()

        if not contract:
            patient_info = self.medsenger_api.get_patient_info(contract_id)

            try:
                patient_id = int(patient_info['id'])
            except:
                raise Exception("No patient info, contract_id = {}".format(contract_id))

            patient = Patient.query.filter_by(id=patient_id).first()
            if not patient:
                patient = Patient(id=patient_id)
                self.db.session.add(patient)

            contract = Contract(id=contract_id, patient_id=patient.id, clinic_id=clinic_id)
            self.db.session.add(contract)

        contract.is_active = True
        contract.clinic_id = clinic_id
        contract.agent_token = self.medsenger_api.get_agent_token(contract_id).get('agent_token')

        self.__commit__()

        return contract
Beispiel #8
0
def resolve_bet(txn, bidder, outcome, price, amount, yes_dir):
    matching_bids = [
        b for b in outcome.bids
        if b.yes_bid != yes_dir and b.price >= 100 - price
    ]
    matching_bids = list(
        sorted(matching_bids, key=lambda b: (-b.price, b.bid_id)))
    while matching_bids and amount:
        bid = matching_bids.pop(0)

        shares_matched = min(amount, bid.amount)
        amount -= shares_matched

        c1 = Contract(outcome=outcome,
                      bidder=bidder,
                      price=100 - bid.price,
                      amount=shares_matched,
                      yes_contract=yes_dir)
        c2 = Contract(outcome=outcome,
                      bidder=bid.bidder,
                      price=bid.price,
                      amount=shares_matched,
                      yes_contract=not yes_dir)
        if shares_matched == bid.amount:
            txn.delete(bid)
        else:
            bid.amount -= shares_matched
        txn.add(c1)
        txn.add(c2)
    if amount:
        existing = txn.query(Bid).filter_by(bidder=bidder,
                                            outcome=outcome,
                                            price=price,
                                            yes_bid=yes_dir).first()
        if existing:
            existing.amount += amount
        else:
            bid = Bid(outcome=outcome,
                      bidder=bidder,
                      price=price,
                      amount=amount,
                      yes_bid=yes_dir)
            txn.add(bid)
Beispiel #9
0
 def post():
     try:
         parser = reqparse.RequestParser()
         parser.add_argument('title')
         parser.add_argument('body')
         parser.add_argument('usage_limit', type=int)
         data = parser.parse_args(strict=True)
         contract = Contract(**data)
         db.session.add(contract)
         db.session.commit()
     except Exception as e:
         abort(400, message=str(e))
     return serialize_contract(contract), 201
Beispiel #10
0
def contract(id):
    contracts = Contract.get_by_idowner(current_user.id) #traigo todos los contratos del que este usuario es dueño
    form = ContractForm()
    if form.validate_on_submit():
        title = form.title.data
        description = form.description.data
        price = form.price.data
        wallet = Wallet.get_by_id(current_user.id)
        contract_address = newContract(title, price, wallet.key) #inicio contrato y creo en la base de datos
        contract = Contract(owner_id= current_user.id, address = contract_address, title = title, description = description, price = price)
        contract.save()
        Contract.onSale_True(contract)
        return redirect(url_for('contract'))
    return render_template('contract.html', contracts=contracts, form=form)
Beispiel #11
0
def monitor_receipt_and_contract():
    """
    监听 kafka 交易数据,出现新数据时,从 web3 获取 receipt
    :return:
    """
    if not config.get('kafka', 'transaction_topic', fallback=None):
        logger_err.error(
            'config.ini 中没有 transaction_topic 参数,退出 monitor_receipt_and_contract 任务'
        )
        return
    elif not config.get('kafka', 'receipt_topic', fallback=None):
        logger_err.error(
            'config.ini 中没有 receipt_topic 参数,退出 monitor_receipt_and_contract 任务'
        )
        return
    elif not config.get('kafka', 'contract_topic', fallback=None):
        logger_err.error(
            'config.ini 中没有 contract_topic 参数,退出 monitor_receipt_and_contract 任务'
        )
        return
    consumer = kafka_consumer(config.get('kafka', 'transaction_topic'),
                              group_id='monitor_receipt')
    last_block_height = None
    tx_cnt = 0  # 已处理的交易数
    for msg in consumer:
        tx = msg.value

        current_block_height = tx["block_number"]
        if last_block_height != current_block_height:
            logger.info(f'区块 {last_block_height} 共处理交易 {tx_cnt} 笔')
            logger.info(f'开始处理区块高度 {current_block_height} 下各交易的 receipt')
            last_block_height = current_block_height
            tx_cnt = 1
        else:
            tx_cnt += 1

        try:
            receipt = w3.eth.getTransactionReceipt(tx['hash'])
        except TransactionNotFound:
            logger_err.error(
                f'在区块高度 {current_block_height} 中找不到交易 {tx["hash"]}')
            continue

        Receipt(data=receipt).save()
        if receipt.get('contractAddress'):
            logger.info(f'在区块高度为 {current_block_height} 的交易 {tx["hash"]} 中'
                        f'发现新创建合约 {receipt.get("contractAddress")}')
            Contract(data=receipt,
                     block_number=receipt.get('blockNumber')).save()
Beispiel #12
0
def add_contract():

    body = request.json
    id_ = body['id_']
    vendor_name = body['vendor_name']
    contract_start_date = body['contract_start_date']
    contract_end_date = body['contract_end_date']

    try:
        contract = Contract(
            vendor_name=vendor_name,
            id_=id_,
            contract_start_date=contract_start_date,
            contract_end_date=contract_end_date,
        )

        db.session.add(contract)
        db.session.commit()
        return "add contract. contract id={}".format(Contract.contract_id), 200

    except Exception as e:
        return (str(e)), 400
Beispiel #13
0
    def post(self):
        request_dict = request.get_json()
        if not request_dict:
            response = {'message': 'No input data provided'}
            return response, status.HTTP_400_BAD_REQUEST
        errors = contract_schema.validate(request_dict)
        if errors:
            return errors, status.HTTP_400_BAD_REQUEST
        try:
            rule_name = request_dict['rule']['name']
            rule = Rule.query.filter_by(name=rule_name).first()
            if rule is None:
                # Create a new rule
                rule = Rule(name=rule_name,
                            f_operand=request_dict['f_operand'],
                            s_operand=request_dict['s_operand'],
                            operator=request_dict['operator'],
                            coefficient=request_dict['coefficient'])
                db.session.add(rule)
            # create a new contract
            contract = Contract(contract_name=request_dict['contract_name'],
                                information=request_dict['information'],
                                rule=rule)

            # requests.put('http://0.0.0.0/{port}/projects', jsonify={
            #     "project_name": 'project_name',
            #     "contract_id": UUID,
            #     status: status.HTTP_201_CREATED
            # })

            contract.add(contract)
            query = Contract.query.get(contract.id)
            result = contract_schema.dump(query).data
            return result, status.HTTP_201_CREATED
        except SQLAlchemyError as e:
            db.session.rollback()
            resp = jsonify({"error": str(e)})
            return resp, status.HTTP_400_BAD_REQUEST
Beispiel #14
0
from app import db
from models import Contract


''' Sunrise''' 


contractName = Contract()
contractName.contract_name =""
contractName.monthly_price =0#setvalues
contractName.operator =""
contractName.age_limit =0
contractName.duration= 0#setvalues

#calls
# --national
contractName.limit_same_operator_calls_nat=0#setvalues ##in minutes
contractName.limit_other_operator_calls_nat=0#setvalues ##in minutes
contractName.limit_fixed_networks_calls_nat=0 
contractName.limit_national_calls= 0
# --international
contractName.limit_outgoing_international_calls_fromCH=0#setvalues
contractName.limit_calls_at_abroad = 0#setvalues #TODO does it include incoming calls as well? 
#standard rates
contractName.rate_call_in_ch = 0.0
contractName.rate_chargable_call_duration = 0#setvalues
contractName.rate_calls_to_abroad = 0.0
contractName.rate_incoming_call_at_abroad = 0.0
contractName.rate_call_from_abroad_to_abroad = 0.0
contractName.rate_call_from_abroad_to_CH = 0.0
#--------------------------------------------------------------------------
Beispiel #15
0
def upload():
    """ Retrieving the file from the request object """ 
    
    # creation of the folder on disk and upload the file selected
    target=os.path.join(APP_ROOT,"upload")
    
    if not os.path.isdir(target):
        os.mkdir(target)

    try :

        file=request.files["InputFile"]
        filename=file.filename
        destination="/".join((target,filename))
        file.save(destination)

        myTable=request.form["inputTable"]
        recImported=0
        
        # Management of the scripts
        if myTable=="Script" :
            with open(destination,"r") as f:
                for line in f:
                    # Init the variables for the process
                    fields=[]
                    fields=line.split(",")

                    # Retrieving the values of the fields
                    if len(fields)== 5 :
                        myScript=Script()
                        myScript.scriptname=fields[0]
                        myScript.scriptdescription=fields[1]
                        myScript.scripttechnology=fields[2]
                        myScript.businessowner=fields[3]
                        myScript.executionfrequency=fields[4]
                        myScript.save()
                        recImported+=1
            flash('Congratulations, {} Script(s) records have been imported recently !!! '.format(recImported), 'message')

        # Management of the scripts
        if myTable=="Application" :
            with open(destination,"r") as f:
                for line in f:
                    # Init the variables for the process
                    fields=[]
                    fields=line.split(",")

                    # Retrieving the values of the fields
                    if len(fields)== 8 :
                        myApplication=Application()
                        myApplication.systemname=fields[0]
                        myApplication.systemdescription=fields[1]
                        myApplication.systemtechnology=fields[2]
                        myApplication.systemprovider=fields[3]
                        myApplication.systemowner=fields[4]
                        myApplication.systemstatus=fields[5]
                        myApplication.systemurl=fields[6]
                        myApplication.systemcategory=fields[7]
                        myApplication.save()
                        recImported+=1
            flash('Congratulations, {} Application(s) records have been imported recently !!! '.format(recImported), 'message')

        # Management of the scripts
        if myTable=="Contract" :
            with open(destination,"r") as f:
                for line in f:
                    # Init the variables for the process
                    fields=[]
                    fields=line.split(",")

                    # Retrieving the values of the fields
                    if len(fields)== 8 :
                        myContract=Contract()
                        myContract.contractref=fields[0]
                        myContract.systemname=fields[1]
                        myContract.contractrenewtype=fields[2]
                        myContract.contractcost=fields[3]
                        myContract.contractstartingdate=fields[4]
                        myContract.contractendingdate=fields[5]
                        myContract.contractcomment=fields[6]
                        mystring=fields[7]
                        mystring=mystring[:-2]
                        myContract.contractyear=int(mystring)
                        myContract.save()
                        recImported+=1
            flash('Congratulations, {} Contract(s) records have been imported recently !!! '.format(recImported), 'message')


    except:
        flash('Sorry, check the inputs of the importation process !!! ', 'error')
        return redirect(url_for('menu'))

    return redirect(url_for('menu'))
Beispiel #16
0
def create_challenge(new_id, short_name, full_name):
    # Create the new entry
    new_contract = Contract(contract_id=new_id,
                            challenge_name=full_name,
                            short_name=short_name)
    new_contract.put()
Beispiel #17
0
def create_contract():

    try:
        treatment_start = parser.parse(request.json['treatment_start']).date()

        # Find or create insurer
        insurer_name = request.json['insurer']
        match = db.session.query(Insurer) \
            .filter(Insurer.name == insurer_name) \
            .first()

        if match:
            insurer = match
        else:
            insurer = Insurer(name=insurer_name)

        # Find or create manufacturer
        manufacturer_name = request.json['manufacturer']
        match = db.session.query(Producer) \
            .filter(Producer.name == manufacturer_name) \
            .first()

        if match:
            manufacturer = match
        else:
            manufacturer = Producer(name=manufacturer_name)

        # Find or create patient
        patient_surname = request.json['patient_surname']
        patient_name = request.json['patient_name']
        patient_birthday = parser.parse(
            request.json['patient_birthday']).date()
        patient_cancer_stage = CancerStage(
            request.json['patient_cancer_stage'])

        # Check if patient is young enough for enrollment
        patient_age = get_age(patient_birthday)
        if patient_age >= 55:
            return Response(
                f"{{'Error':'Patient does not fullfill enrollment criteria: Age {patient_age} >= 55'}}",
                status=400,
                mimetype='application/json')

        match = db.session.query(Patient) \
            .filter(Patient.name == patient_name) \
            .filter(Patient.surname == patient_surname) \
            .filter(Patient.birthday == patient_birthday) \
            .first()

        if match:
            patient = match
        else:
            patient = Patient(name=patient_name,
                              surname=patient_surname,
                              birthday=patient_birthday,
                              cancer_stage=patient_cancer_stage)

        # Find or create product configuration
        product_brand = request.json['product_brand']
        product_name = request.json['product_name']
        product_units = request.json['product_units']
        product_baseprice = request.json['product_baseprice']
        match = db.session.query(Product) \
            .filter(Product.brand == product_brand) \
            .filter(Product.product == product_name) \
            .filter(Product.units == product_units) \
            .filter(Product.baseprice == product_baseprice) \
            .first()

        if match:
            product = match
        else:
            product = Product(brand=product_brand,
                              product=product_name,
                              units=product_units,
                              baseprice=product_baseprice)

        # Find or create payable amounts configuration
        os = request.json['os']
        no_os = request.json['no_os']
        pfs = request.json['pfs']
        no_pfs = request.json['no_pfs']
        match = db.session.query(PayableAmount) \
            .filter(PayableAmount.os_after_12_months == os) \
            .filter(PayableAmount.no_os_after_12_months == no_os) \
            .filter(PayableAmount.pfs_after_9_months == pfs) \
            .filter(PayableAmount.no_pfs_after_9_months == no_pfs) \
            .first()

        if match:
            payable_amounts = match
        else:
            payable_amounts = PayableAmount(os_after_12_months=os,
                                            no_os_after_12_months=no_os,
                                            pfs_after_9_months=pfs,
                                            no_pfs_after_9_months=no_pfs)

        new_contract = Contract(insurer=insurer,
                                producer=manufacturer,
                                product=product,
                                patient=patient,
                                status='ongoing',
                                treatment_start=treatment_start,
                                payable_amounts=payable_amounts)

        # Check if contract is already finished -> simulation purposes
        payable = check_contract_status(new_contract.to_dict(), [])

        if not payable == -1:
            # No events could have been generated at contract creation -> bill for 9 months PFS
            new_contract.amount = 9 * (product_baseprice * payable)
            new_contract.status = 'finished'

        db.session.add(new_contract)
        db.session.commit()

        return Response('{"status": "ok"}', status=200)

    except:

        return Response('{"status": "error"}', status=500)
Beispiel #18
0
def add_contract_into_db(data: dict):
    """
    Запись внесенных на странице contract_add.html данных в БД

    Args:
        data (dict): словарь с данными нового договора

    Returns:
        запись нового договора в БД
    """

    # проверка на заполнение всех полей
    for k, v in data.items():
        if not k or not v:
            print(f'параметр: {k} не заполнен')
            return False

    # валидадция введеного id агента
    agent_query = session.query(Agent).filter_by(name=data['agent_name']).all()
    if agent_query:
        agent_id = agent_query[0].id
        print(f'Выбран контрагент: {agent_query[0].name}, id: {agent_id}')
    else:
        print('Не вероно указано имя контрагента...\n')
        eel.alert_message('Не вероно указано имя контрагента...')
        return False

    # валидация номера договора
    contract_query = session.query(Contract).filter_by(
        agent_id=agent_id, number=data['number']).all()

    if contract_query:
        eel.alert_message(
            f'У контрагента {agent_query[0].name} уже есть договор № {contract_query[0].number}'
        )
        print(
            f'У контрагента {agent_query[0].name} уже есть договор № {contract_query[0].number}'
        )
        return False

    start_year = int(data['date_of_start'].split('.')[2])
    start_month = int(data['date_of_start'].split('.')[1])
    start_day = int(data['date_of_start'].split('.')[0])
    date_of_start = date(start_year, start_month, start_day)

    end_year = int(data['date_of_end'].split('.')[2])
    end_month = int(data['date_of_end'].split('.')[1])
    end_day = int(data['date_of_end'].split('.')[0])
    date_of_end = date(end_year, end_month, end_day)

    validity = (date_of_end - date_of_start).days
    now = datetime.now().date()
    days_passed = (now - date_of_start).days
    days_left = (date_of_end - now).days

    new_contract = Contract(agent_id=agent_id,
                            number=data['number'],
                            description=data['description'],
                            contract_sum=data['contract_sum'],
                            contract_balance=data['contract_sum'],
                            date_of_conclusion=data['date_of_conclusion'],
                            date_of_start=data['date_of_start'],
                            date_of_end=data['date_of_end'],
                            validity=validity,
                            days_passed=days_passed,
                            days_left=days_left)

    session.add(new_contract)
    session.commit()
    eel.alert_message('Новый договор добавлен!')
    # print('Новый договор добавлен!')
    return True
Beispiel #19
0
def fill_db():

    # Add example products
    product_conf_1 = Product(brand="ABC",
                             product="vial 10mg/ml",
                             units=10,
                             baseprice=1000)
    product_conf_2 = Product(brand="ABC",
                             product="vial 10mg/ml",
                             units=20,
                             baseprice=1800)
    product_conf_3 = Product(brand="ABC",
                             product="vial 10mg/ml",
                             units=30,
                             baseprice=2500)
    product_conf_4 = Product(brand="ABC",
                             product="vial 20mg/ml",
                             units=10,
                             baseprice=1000)
    product_conf_5 = Product(brand="ABC",
                             product="vial 20mg/ml",
                             units=20,
                             baseprice=2700)
    product_conf_6 = Product(brand="ABC",
                             product="vial 20mg/ml",
                             units=30,
                             baseprice=4100)

    products = [
        product_conf_1, product_conf_2, product_conf_3, product_conf_4,
        product_conf_5, product_conf_6
    ]

    for product in products:
        db.session.add(product)

    # Add patient event types
    patient_event_type_1 = PatientEventType(event_name="progressed")
    patient_event_type_2 = PatientEventType(event_name="dead")

    db.session.add(patient_event_type_1)
    db.session.add(patient_event_type_2)

    # Add default payable amount configuration
    payable_amount_conf = PayableAmount(os_after_12_months=0.75,
                                        no_os_after_12_months=0.35,
                                        pfs_after_9_months=0.85,
                                        no_pfs_after_9_months=0.40)

    db.session.add(payable_amount_conf)

    # Add manufacturers
    manufacturer_1 = Producer(name="Roche")
    manufacturer_2 = Producer(name="Novartis")
    manufacturer_3 = Producer(name="Orion")

    db.session.add(manufacturer_1)
    db.session.add(manufacturer_2)
    db.session.add(manufacturer_3)

    # Add insurers
    insurer_1 = Insurer(name="Helsana")
    insurer_2 = Insurer(name="Swica")
    insurer_3 = Insurer(name="OEKK")

    db.session.add(insurer_1)
    db.session.add(insurer_2)
    db.session.add(insurer_3)

    # Add patients
    patient_1 = Patient(surname="Muster",
                        name="Max",
                        birthday=parser.parse('1990-01-01'),
                        cancer_stage=CancerStage.two)
    patient_2 = Patient(surname="Muller",
                        name="Jan",
                        birthday=parser.parse('1998-01-01'),
                        cancer_stage=CancerStage.zero)
    patient_3 = Patient(surname="Zindel",
                        name="Alice",
                        birthday=parser.parse('1985-06-01'),
                        cancer_stage=CancerStage.three)

    # Add example contracts
    contract_1 = Contract(producer=manufacturer_1,
                          insurer=insurer_1,
                          product=product_conf_1,
                          payable_amounts=payable_amount_conf,
                          patient=patient_1,
                          treatment_start=parser.parse('2020-08-01'),
                          status="ongoing")
    contract_2 = Contract(producer=manufacturer_2,
                          insurer=insurer_2,
                          product=product_conf_1,
                          payable_amounts=payable_amount_conf,
                          patient=patient_2,
                          treatment_start=parser.parse('2020-04-30'),
                          status="ongoing")
    contract_3 = Contract(producer=manufacturer_1,
                          insurer=insurer_1,
                          product=product_conf_1,
                          payable_amounts=payable_amount_conf,
                          patient=patient_3,
                          treatment_start=parser.parse('2020-11-30'),
                          status="ongoing")

    db.session.add(contract_1)
    db.session.add(contract_2)
    db.session.add(contract_3)
    db.session.commit()
Beispiel #20
0
    def on_request_contractsinfo(self, code):
        outblock = self.query.tr['outblock']

        timediff = timedelta(
            hours=int(self.query.get_field_data(outblock, 'TimeDiff', 0)))

        ovsstrday = self.query.get_field_data(outblock, 'OvsStrDay', 0)
        opendate = ovsstrday + self.query.get_field_data(
            outblock, 'OvsStrTm', 0)
        ovsendday = self.query.get_field_data(outblock, 'OvsEndDay', 0)
        closedate = ovsendday + self.query.get_field_data(
            outblock, 'OvsEndTm', 0)
        pcode = self.query.get_field_data(outblock, 'BscGdsCd', 0)  #상품코드
        c = {
            'symbol':
            self.query.get_field_data(outblock, 'Symbol', 0),  #월물코드
            'name':
            self.query.get_field_data(outblock, 'SymbolNm', 0),  #월물명
            'ecprice':
            self.query.get_field_data(outblock, 'EcPrc', 0),  #정산가격
            'appldate':
            datetime.strptime(
                self.query.get_field_data(outblock, 'ApplDate', 0),
                '%Y%m%d'),  #종목배치수신일
            'eccd':
            self.query.get_field_data(outblock, 'EcCd', 0),  #정산구분
            'eminicode':
            self.query.get_field_data(outblock, 'EminiCd', 0),  #Emini구분
            'year':
            self.query.get_field_data(outblock, 'LstngYr', 0),  #상장년
            'month':
            self.query.get_field_data(outblock, 'LstngM', 0),  #상장월
            'seqno':
            self.query.get_field_data(outblock, 'SeqNo', 0),  #월물순서
            'expiration':
            datetime.strptime(self.query.get_field_data(outblock, 'MtrtDt', 0),
                              '%Y%m%d'),  #만기일자
            'final_tradeday':
            datetime.strptime(
                self.query.get_field_data(outblock, 'FnlDlDt', 0),
                '%Y%m%d'),  #최종거래일
            'opendate':
            datetime.strptime(opendate, '%Y%m%d%H%M%S') -
            timediff,  #거래시작일자(한국)
            'closedate':
            datetime.strptime(closedate, '%Y%m%d%H%M%S') -
            timediff,  #거래종료일자(한국)
            'ovsstrday':
            datetime.strptime(ovsstrday, '%Y%m%d'),  #거래시작일 (현지)
            'ovsendday':
            datetime.strptime(ovsendday, '%Y%m%d'),  #거래종료일 (현지)
            'is_tradable':
            True if self.query.get_field_data(outblock, 'DlPsblCd',
                                              0) == '1' else False  #거래가능구분코드
        }

        # 신규월물 추가 및 업데이트
        if not self.products[pcode].get(c['symbol']):
            self.products[pcode][c['symbol']] = Contract(
                c['symbol'], c['name'])
            self.logger.info(f"New contract {c['name']} has created")
        self.products[pcode][c['symbol']].updateinfo(c)

        if self.contracts:
            self.request_contractsinfo()
        else:
            self.logger.info("Contract information updated")
            self.next_step(4)
Beispiel #21
0
def delete_contract(request):
    contr = Contract(user=request.user,
                     id=int(request.path_info.split("/")[3]))
    contr.delete()
    return redirect("/profile/")