예제 #1
0
async def response_getmany_stt(request=None, Model=None, result=None, **kw):
    if result is not None and "objects" in result:
        objects = to_dict(result["objects"])
        datas = []
        i = len(objects)
        page = request.args.get("page", None)
        results_per_page = request.args.get("results_per_page", None)
        currentUser = await current_user(request)
        if currentUser is None:
            return json(
                {
                    "error_code": "PERMISSION_DENY",
                    "error_message": "Hết phiên làm việc!"
                },
                status=520)
        if page is not None and results_per_page is not None and int(
                page) != 1:
            i = i - int(results_per_page) * int(page)
        for obj in objects:
            if obj is not None:
                # paymentdetails = db.session.query(PaymentDetails).filter(PaymentDetails.payment_id == to_dict(obj)['id']).all()
                # thanhtoan = 0;
                # for _ in paymentdetails:
                #     thanhtoan = thanhtoan + to_dict(_)['amount']
                # if obj['amount'] > thanhtoan:
                #     to_dict(obj)["status"]  = "slacking"
                # elif obj['amount'] == thanhtoan:
                #     to_dict(obj)["status"]  = "finish"
                # elif obj['amount'] < thanhtoan:
                #     to_dict(obj)["status"]  = "wrong"
                obj_tmp = to_dict(obj)
                obj_tmp["stt"] = i
                i = i - 1
                datas.append(obj_tmp)
        result = datas
예제 #2
0
async def check_notify(request):
    uid_current = current_uid(request)
    if uid_current is None:
        return json({"error_code": "SESSION_EXPIRED", "error_message": "Hết phiên làm việc, vui lòng đăng nhập lại"}, status=520)
    else:
        count = 0
        notify_user = db.session.query(NotifyUser).\
        filter(and_(NotifyUser.user_id == uid_current, NotifyUser.read_at == None)).count()
        if notify_user is not None:
            count = notify_user
        check_all =db.session.query(NotifyUser, Notify).filter(and_(NotifyUser.user_id == uid_current, NotifyUser.notify_id == Notify.id)).\
            filter(NotifyUser.read_at.is_(None)).order_by(desc(NotifyUser.updated_at)).all()
        check_video = None
        check_new = None
        noti_user = None

        for item, notify in check_all:
            if notify.type == "call_video":
                check_video = notify
                noti_user = item
                break
            else:
                if (check_new is None):
                    check_new = to_dict(notify)
                    noti_user = item
        if check_video is not None:
            check_new = to_dict(check_video)

        if noti_user is not None and noti_user.read_at is None:
            notify_info = db.session.query(NotifyUser).filter(NotifyUser.id ==noti_user.id).first()
            if notify_info is not None:
                notify_info.read_at = floor(time.time())
                db.session.commit()
    return json({"error_message": "successful", "data": count, "notify": to_dict(check_new)})
async def send_notify_single(user_id, title, content, record_type, action, id_url):
# type_action
    if(title is None or title == ""):
        title = "Thông báo"
    notify_record = Notify()
    notify_record.title = title
    notify_record.content = content
    notify_record.type = record_type
    notify_record.action = None

    notify_record.url = record_type+"/model?id="+str(id_url)
    db.session.add(notify_record)
    db.session.flush()

    firebase_token = redisdb_firebase.get("notify_token:" + str(user_id))
    print("notify_record=====",to_dict(notify_record), "user_id====",user_id)
    if firebase_token is not None:
        firebase_token = firebase_token.decode('utf8')
        notify_user = NotifyUser()
        notify_user.user_id = user_id
        notify_user.notify_id = notify_record.id
        notify_user.notify_at = floor(time.time())
        notify_user.read_at = None
        db.session.add(notify_user)
        db.session.commit()
        await send_firebase_notify([firebase_token], title, to_dict(notify_record))
예제 #4
0
def response_userinfo(user, **kw):
    if user is not None:
        # employee = to_dict(user.employee)
        group_last_access = user.group_last_access

        user_info = to_dict(user)
        if user.group_last_access_id is not None:
            user_info['group_last_access_id'] = str(user.group_last_access.id)
            user_info['group_last_access'] = to_dict(group_last_access)
        else:
            user_info['group_last_access_id'] = None
            user_info['group_last_access'] = None
        # user_info['employee'] = employee
        exclude_attr = [
            "password", "salt", "created_at", "created_by", "updated_at",
            "updated_by", "deleted_by", "deleted_at", "deleted",
            "facebook_access_token", "phone_country_prefix",
            "phone_national_number", "last_login_at", "current_login_at",
            "last_login_ip", "current_login_ip", "login_count"
        ]

        for attr in exclude_attr:
            if attr in user_info:
                del (user_info[attr])

        # permision
        # roles = [{"id": str(role.id), "role_name": role.role_name}
        #          for role in user.roles]

        # roleids = [role.id for role in user.roles]
        # user_info['roles'] = roles
        return user_info
    return None
예제 #5
0
async def get_unit_name(request=None, Model=None, result=None, **kw):
    if result is not None and "objects" in result:
        objects = to_dict(result["objects"])
        datas = []
        i = 1
        page = request.args.get("page", None)
        results_per_page = request.args.get("results_per_page", None)
        currentUser = await current_user(request)
        if currentUser is None:
            return json(
                {
                    "error_code": "PERMISSION_DENY",
                    "error_message": "Hết phiên làm việc!"
                },
                status=520)
        if page is not None and results_per_page is not None and int(
                page) != 1:
            i = i + int(results_per_page) * int(page)
        for obj in objects:
            if obj is not None:
                obj_tmp = to_dict(obj)
                unit = db.session.query(Unit.name).filter(
                    and_(Unit.id == to_dict(obj)['unit_exchange'])).first()
                obj_tmp["stt"] = i
                obj_tmp["unit_name"] = unit
                i = i + 1
                datas.append(obj_tmp)
        result = datas
def get_baocao_bcc_quanhuyen(nambaocao, loaikybaocao, kybaocao, quanhuyen_id):
    results = []
    records_xaphuong = db.session.query(TienDoKeHoachBCC).filter(and_(TienDoKeHoachBCC.quanhuyen_id == quanhuyen_id, \
                                                TienDoKeHoachBCC.loaikybaocao == loaikybaocao, \
                                                TienDoKeHoachBCC.kybaocao == kybaocao, \
                                                TienDoKeHoachBCC.nambaocao == nambaocao),\
                                                TienDoKeHoachBCC.tuyendonvi == 'xa').all()
    if records_xaphuong is not None:
        for item_xaphuong in records_xaphuong:
            baocao_xaphuong = to_dict(item_xaphuong)
            if (item_xaphuong.xaphuong is not None):
                baocao_xaphuong['xaphuong'] = to_dict(item_xaphuong.xaphuong)
            records_thonxom = db.session.query(TienDoKeHoachBCC).filter(and_(TienDoKeHoachBCC.xaphuong_id == baocao_xaphuong['xaphuong_id'], \
                                                TienDoKeHoachBCC.loaikybaocao == loaikybaocao, \
                                                TienDoKeHoachBCC.kybaocao == kybaocao, \
                                                TienDoKeHoachBCC.nambaocao == nambaocao),\
                                                TienDoKeHoachBCC.tuyendonvi == 'thon').all()
            baocao_xaphuong["thon"] = []
            if records_thonxom is not None:
                for bc_thonxom in records_thonxom:
                    baocao_thonxom = to_dict(bc_thonxom)
                    baocao_xaphuong["thon"].append(baocao_thonxom)
            else:
                baocao_xaphuong["thon"] = []
            results.append(baocao_xaphuong)
    else:
        results = []

    return results
예제 #7
0
async def response_getmany_stt(request=None, Model=None, result=None, **kw):
    if result is not None and "objects" in result:
        objects = to_dict(result["objects"])
        datas = []
        i = 1
        page = request.args.get("page", None)
        results_per_page = request.args.get("results_per_page", None)
        currentUser = await current_user(request)
        if currentUser is None:
            return json(
                {
                    "error_code": "PERMISSION_DENY",
                    "error_message": "Hết phiên làm việc!"
                },
                status=520)
        if page is not None and results_per_page is not None and int(
                page) != 1:
            i = i + int(results_per_page) * int(page)
        for obj in objects:
            if obj is not None:
                obj_tmp = to_dict(obj)
                obj_tmp["stt"] = i
                i = i + 1
                datas.append(obj_tmp)
        result = datas
예제 #8
0
async def luucacbuoc(request):
    data = request.json
    print("---------------------buoc kiem tra-------------------",
          data['step'])
    print("---------------------equipmentinspectionform_id-------------------",
          data['equipmentinspectionform_id'])
    buoc = data['step']
    idbangkiemtra = data['equipmentinspectionform_id']
    step = db.session.query(Step).filter(
        and_(Step.equipmentinspectionform_id == idbangkiemtra,
             Step.step == buoc)).first()
    print("---------------------to_dict(step)-------------------",
          to_dict(step))
    if step is not None:
        step.note = data["note"]
        step.status = data["status"]
        step.time = data["time"]
        step.picture = data["picture"]
        db.session.commit()
        return json(to_dict(step))
    else:
        new_buockiemtra = Step()
        new_buockiemtra.note = data["note"]
        new_buockiemtra.step = data["step"]
        new_buockiemtra.status = data["status"]
        new_buockiemtra.picture = data["picture"]
        new_buockiemtra.time = data["time"]
        new_buockiemtra.equipmentinspectionform_id = data[
            "equipmentinspectionform_id"]
        db.session.add(new_buockiemtra)
        db.session.commit()
        return json(to_dict(new_buockiemtra))
예제 #9
0
async def write_file(file, fileId, attrs, uid_current):
    url = app.config['FILE_SERVICE_URL']
    fsroot = app.config['FS_ROOT_FILE']
    if not os.path.exists(fsroot):
        os.makedirs(fsroot)
    file_name = os.path.splitext(file.name)[0]
    extname = os.path.splitext(file.name)[1]

    BLOCKSIZE = 65536
    sha256 = hashlib.sha256()
    file_data = file.body
    data_length = len(file_data)
    if (data_length <= 0):
        return json(
            {
                "error_code": "Error",
                "error_message": "File không hợp lệ"
            },
            status=520)
    elif (data_length < BLOCKSIZE):
        BLOCKSIZE = data_length

    # f = file.body.open('rb')
    # if f.multiple_chunks():
    #     for chunk in f.chunks():
    #         sha256.update(chunk)
    # else:
    #         sha256.update(f.read())
    # f.close()
    sha256.update(file_data)
    # file_buffer = file_data.read(BLOCKSIZE)
    # while len(file_buffer) > 0:
    #     sha256.update(file_buffer)
    #     file_buffer = file_data.read(BLOCKSIZE)

    str_sha256 = sha256.hexdigest()
    check_exist = db.session.query(FileInfo).filter(
        FileInfo.sha256 == str_sha256).first()
    if check_exist is not None:
        return json(to_dict(check_exist))

    async with aiofiles.open(fsroot + str_sha256 + extname, 'wb+') as f:
        await f.write(file.body)
    f.close()

    if fileId is None:
        fileId = str(uuid.uuid4())
    fileInfo = FileInfo()
    fileInfo.id = fileId
    fileInfo.sha256 = str_sha256
    fileInfo.user_id = uid_current
    fileInfo.name = file_name
    fileInfo.extname = extname
    fileInfo.link = str(url) + "/" + str(str_sha256) + str(extname)
    fileInfo.attrs = attrs
    fileInfo.size = data_length
    fileInfo.kind = "normal"
    db.session.add(fileInfo)
    db.session.commit()
    return json(to_dict(fileInfo), status=200)
예제 #10
0
async def login(request):
    data = request.json
    if data is None or data.get('username', None) is None or data.get(
            'password', None) is None:
        return json(
            {
                'error_code': 'AUTH_FAILED',
                'error_message': 'Username, password are required'
            },
            status=523)

    username = data.get('username', None)
    password = data.get('password', None)

    login_user = db.session.query(User).filter(or_(User.phone == convert_phone_number(username),\
                                                    User.email == str(username).lower())).first()

    if login_user is None:
        return json(
            {
                'error_code': 'E523',
                'error_message': 'Tài khoản không tồn tại.'
            },
            status=523)

    if auth.verify_password(password, login_user.password,
                            login_user.salt) == False:
        return json(
            {
                'error_code': 'E523',
                'error_message': 'Mật khẩu không chính xác.'
            },
            status=523)

    tenant_dict = to_dict(login_user.tenant)
    for key in exclude_attrs:
        if key in tenant_dict:
            del tenant_dict[key]

    login_user = to_dict(login_user)
    for key in exclude_attrs:
        if key in login_user:
            del login_user[key]

    request['session']['current_tenant_id'] = tenant_dict.get('id')
    login_user['tenant'] = tenant_dict
    auth.login_user(request, login_user)

    return json({
        'id': str(login_user.get('id')),
        'display_name': login_user.get('display_name'),
        'phone': login_user.get('phone'),
        'email': login_user.get('email'),
        'gender': login_user.get('gender'),
        'avatar': login_user.get('avatar'),
        'tenant': login_user.get('tenant'),
        'current_tenant_id': tenant_dict.get('id')
    })
예제 #11
0
async def reponse_capxa_single(request=None, Model=None, result=None, **kw):
    obj = to_dict(result)
    capthon = db.session.query(CapThon).filter(
        CapThon.tenxa_id == obj['tenxa_id']).all()
    thons = []
    for thon in capthon:
        thons.append(to_dict(thon))
    obj['capthon'] = thons
    result = obj
예제 #12
0
async def reponse_caphuyen_single(request=None, Model=None, result=None, **kw):
    obj = to_dict(result)
    capxa = db.session.query(CapXa).filter(
        CapXa.tenxa_id == obj['tenhuyen_id']).all()
    capxas = []
    for xas in capxa:
        capxas.append(to_dict(xas))
    obj['capxa'] = capxas
    result = obj
예제 #13
0
def pre_put_user_donvi(request=None, instance_id=None, data=None, **kw):
    check_user = User.query.filter(User.id == data["user_id"]).first()
    print("check_user===", to_dict(check_user))
    checkemail = UserDonvi.query.filter(
        and_(UserDonvi.email == data["email"],
             UserDonvi.id != data["id"])).first()
    if checkemail is not None:
        return json(
            {
                "error_code":
                "PARAMS_ERROR",
                "error_message":
                "Email của người dùng đã tồn tại trong hệ thống, vui lòng chọn Email khác"
            },
            status=520)

    checkphone = UserDonvi.query.filter(
        and_(UserDonvi.phone == data["phone"],
             UserDonvi.id != data["id"])).first()
    if checkphone is not None:
        return json(
            {
                "error_code":
                "PARAMS_ERROR",
                "error_message":
                "Số điện thoại của người dùng đã tồn tại trong hệ thống"
            },
            status=520)

    donvi = db.session.query(DonVi).filter(
        DonVi.id == data["donvi_id"]).first()
    if check_user is not None:
        #         try:
        check_user.email = data["email"]
        check_user.phone = data["phone"]
        print("change.email===", data["email"])
        print("change.phone===", data["phone"])
        db.session.add(check_user)
        db.session.commit()
        re_check_user = db.session.query(User).filter(
            User.id == data["user_id"]).first()
        print("re_check_user===", to_dict(re_check_user))
#         except:
#             return json({"error_code": "PARAMS_ERROR", "error_message": "Số điện thoại hoặc Email của người dùng đã tồn tại trong hệ thống"},status=520)

    if donvi is not None:
        #         try:
        donvi.ten = data["donvi_ten"]
        donvi.captren_id = data["captren_id"]
        donvi.tuyendonvi_id = data["donvi_tuyendonvi_id"]
        donvi.diachi = data["donvi_diachi"]
        donvi.sodienthoai = data["donvi_sodienthoai"]
        donvi.coquanchuquan = data["captren"]["ten"]
        donvi.tinhthanh_id = data["tinhthanh_id"]
        donvi.quanhuyen_id = data["quanhuyen_id"]
        donvi.xaphuong_id = data["xaphuong_id"]
    db.session.commit()
예제 #14
0
def list_warehouse(request):
    data = request.json
    if data is not None:
        warehouse = db.session.query(Warehouse).filter(Warehouse.tenant_id == data).all()
        arr = []
        for wh in warehouse:
                obj= {}
                obj['id'] = to_dict(wh)['id']
                obj['name'] = to_dict(wh)['warehouse_name']
                arr.append(obj)
    return json(arr)
예제 #15
0
async def get_user_with_permission(user):
    user_info = to_dict(user)
    roles = [{
        "id": str(role.id),
        "description": role.description,
        "role_name": role.name
    } for role in user.roles]
    roleids = [role.id for role in user.roles]
    user_info["roles"] = roles
    user_info['donvi'] = to_dict(user.donvi)
    user_info['donvi']['tinhthanh'] = to_dict(user.donvi.tinhthanh)
    user_info['donvi']['quanhuyen'] = to_dict(user.donvi.quanhuyen)
    user_info['donvi']['xaphuong'] = to_dict(user.donvi.xaphuong)

    #check chuong trinh SUP
    check_SUP = db.session.query(DanhSachDonViThuocSUP)
    if (user.donvi.tuyendonvi_id == 2):
        check_SUP = check_SUP.filter(DanhSachDonViThuocSUP.tinhthanh_id ==
                                     user.donvi.tinhthanh_id).first()
    elif (user.donvi.tuyendonvi_id == 3):
        check_SUP = check_SUP.filter(DanhSachDonViThuocSUP.quanhuyen_id ==
                                     user.donvi.quanhuyen_id).first()
    elif (user.donvi.tuyendonvi_id == 4):
        check_SUP = check_SUP.filter(DanhSachDonViThuocSUP.xaphuong_id ==
                                     user.donvi.xaphuong_id).first()
    else:
        check_SUP = None
    if check_SUP is not None:
        user_info["check_SUP"] = 1
    else:
        user_info["check_SUP"] = 0
    #permission:
    perms = Permission.query.filter(Permission.role_id.in_(roleids)).order_by(
        Permission.subject).all()
    permobj = {}

    for perm in perms:
        if perm.subject not in permobj:
            permobj[perm.subject] = {}

        if perm.permission not in permobj[perm.subject]:
            permobj[perm.subject][perm.permission] = perm.value
        elif not permobj[perm.subject][perm.permission]:
            permobj[perm.subject][perm.permission] = perm.value
    user_info["permission"] = permobj
    exclude_attr = ["password", "confirmpassword", "created_at", "created_by", "updated_at", "updated_by",\
                        "deleted_by", "deleted_at", "deleted",\
                        "confirmed_at","last_login_at","current_login_at",\
                        "last_login_ip","current_login_ip","login_count"]

    for attr in exclude_attr:
        del (user_info[attr])
    return user_info
예제 #16
0
def get_task_schedule(request):
    id_schedule = request.args.get("id", None)
    task_schedule = db.session.query(TaskSchedule).filter(
        TaskSchedule.id == id_schedule).first()
    result = to_dict(task_schedule)
    result['task_scheduledetail'] = []
    for task_scheduledetail in task_schedule.task_scheduledetail:
        obj = to_dict(task_scheduledetail)
        obj['tasks_info'] = [
            to_dict(task_info) for task_info in task_scheduledetail.tasks_info
        ]
        result['task_scheduledetail'].append(obj)

    return json(result)
예제 #17
0
def get_topping(parent_item, tenant_id):
    topping = []
    now_time = now_timestamp()
    categories = db.session.query(ItemCategory).join(ItemCategoryRelation).filter(
        ItemCategoryRelation.item_id == parent_item.get('id'),
        ItemCategory.category_type == 'topping',
        ItemCategory.deleted == False,
        ItemCategory.tenant_id == tenant_id
    ).all()
    active_price_list = PriceList.query.filter(and_(PriceList.tenant_id == tenant_id,\
        or_(and_(PriceList.start_time <= now_time,\
                PriceList.end_time >= now_time),\
            PriceList.is_default == True),\
        PriceList.deleted == False)).order_by(PriceList.is_default.desc()).first()

    for category in categories:
        category_dict = to_dict(category)
        category_dict['items'] = []
        items = db.session.query(Item).join(ItemCategoryRelation).filter(
            ItemCategoryRelation.category_id == category_dict.get('id'),
            Item.item_type == 'topping',
            Item.deleted == False, Item.tenant_id == tenant_id,
            Item.active == True).all()
        for item in items:
            item_dict = to_dict(item)

            if active_price_list is not None:
                # QUERY ITEM PRICE LIST
                item_price_list = ItemPriceList.query.filter(and_(ItemPriceList.tenant_id == tenant_id,\
                                                                ItemPriceList.price_list_id == active_price_list.id,\
                                                                ItemPriceList.item_id == item_dict.get('id'))).first()
                if item_price_list is not None:
                    dict_item_price = to_dict(item_price_list)
                    dict_item_price['id'] = str(dict_item_price['id'])
                    item_dict['price_list'] = dict_item_price

            item_dict['topping'] = []
            category_dict['items'].append(item_dict)

        category_item_relations = db.session.query(ItemCategoryRelation).filter(
            ItemCategoryRelation.item_id == parent_item.get('id'),
            ItemCategoryRelation.category_id == category.id
            ).first()
        category_item_relations_dict = to_dict(category_item_relations)
        del category_item_relations_dict['id']
        del category_item_relations_dict['category_id']
        del category_item_relations_dict['item_id']
        topping.append({**category_dict, **category_item_relations_dict})
    return topping
예제 #18
0
async def history(request):
    current_tenant = get_current_tenant(request)
    if current_tenant is None or 'error_code' in current_tenant:
        return json(
            {
                'error_code': 'TENANT_UNKNOWN',
                'error_message': 'Thông tin request không xác định'
            },
            status=523)

    tenant_id = current_tenant.get('id')
    contact_id = request.args.get('contact_id')
    device_id = request.args.get('device_id')

    query_state = [Salesorder.tenant_id == tenant_id]

    # salesorder_query_state = db.session.query(Salesorder).filter(Salesorder.tenant_id == tenant_id)
    if contact_id is not None:
        query_state.append(Salesorder.contact_id == contact_id)
        # salesorder_query_state.filter(Salesorder.contact_id == contact_id)
    if device_id is not None:
        query_state.append(Salesorder.device_id == device_id)
        # salesorder_query_state.filter(Salesorder.device_id == device_id)

    salesorders = db.session.query(Salesorder).filter(*query_state).order_by(
        Salesorder.updated_at.asc()).all()
    # salesorders = salesorder_query_state.all()

    results = []
    for salesorder in salesorders:
        salesorder_dict = to_dict(salesorder)
        salesorder_dict['service'] = to_dict(salesorder.service)
        salesorder_dict['room'] = to_dict(salesorder.room)
        salesorder_dict['provider'] = to_dict(salesorder.provider)
        salesorder_dict['salesorder_items'] = []
        for item in salesorder.salesorder_items.all():
            salesorder_dict['salesorder_items'].append(to_dict(item))

        salesorder_dict['list_status'] = get_service_status(
            salesorder.service.service_no)
        status_name = "done"
        for status in salesorder_dict['list_status']:
            if status.get("sostatus") == salesorder_dict.get("sostatus"):
                status['status'] = status_name
                status_name = "pending"
                continue
            status['status'] = status_name
        results.append(copy.deepcopy(salesorder_dict))
    return json({"results": results}, status=200)
예제 #19
0
def postTaskInfo(request=None, data=None, Model=None):
    uid = auth.current_user(request)
    if uid is not None:
        task_info = request.json
        task_info = createTaskInfo(task_info,uid)
        response = to_dict(task_info)
        response['group'] = to_dict(task_info.group)
        print(response['group'])
        return json(response,status=201)

    else:
        return json({
            "error_code": "USER_NOT_FOUND",
            "error_message":"USER_NOT_FOUND"
        }, status = 520)
예제 #20
0
async def response_debt_calculation(request=None,
                                    Model=None,
                                    result=None,
                                    **kw):
    if result is not None and "objects" in result:
        objects = to_dict(result["objects"])
        datas = []
        i = 1
        page = request.args.get("page", None)
        results_per_page = request.args.get("results_per_page", None)
        if page is not None and results_per_page is not None and int(
                page) != 1:
            i = i + int(results_per_page) * int(page)
        for obj in objects:
            if obj is not None:
                obj_tmp = to_dict(obj)
                if obj_tmp['organization_type'] == "reseller":
                    list = db.session.query(func.sum(
                        GoodsReciept.amount)).filter(
                            and_(
                                GoodsReciept.organization_id == obj_tmp['id'],
                                GoodsReciept.tenant_id ==
                                obj_tmp['tenant_id'])).all()
                if obj_tmp['organization_type'] == "customer":
                    list = db.session.query(func.sum(
                        PurchaseOrder.amount)).filter(
                            and_(
                                PurchaseOrder.workstation_id == obj_tmp['id'],
                                PurchaseOrder.tenant_id ==
                                obj_tmp['tenant_id'])).all()
                payment = db.session.query(func.sum(Payment.amount)).filter(
                    and_(Payment.organization_id == obj_tmp['id'],
                         Payment.tenant_id == obj_tmp['tenant_id'])).all()
                result = 0
                if list[0][0] is not None and payment[0][0] is not None:
                    result = list[0][0] - payment[0][0]
                if payment[0][0] is not None and list[0][0] is None:
                    result = payment[0][0]
                if payment[0][0] is None and list[0][0] is not None:
                    result = list[0][0]
                if payment[0][0] is None and list[0][0] is None:
                    result = 0

                obj_tmp["stt"] = i
                obj_tmp["amount"] = result
                i = i + 1
                datas.append(obj_tmp)
        result = datas
예제 #21
0
async def add_stt(request=None, data=None, result=None, **kw):
    data = []
    for i in range(len(result['objects'])):
        obj_tmp = to_dict(result['objects'][i])
        obj_tmp["stt"] = i + 1
        data.append(obj_tmp)
    result = data
def get_baocao_bcc_xaphuong(nambaocao, loaikybaocao, kybaocao, xaphuong_id):
    results = []
    records_thonxom = db.session.query(TienDoKeHoachBCC).filter(and_(TienDoKeHoachBCC.xaphuong_id == xaphuong_id, \
                                                TienDoKeHoachBCC.loaikybaocao == loaikybaocao, \
                                                TienDoKeHoachBCC.kybaocao == kybaocao, \
                                                TienDoKeHoachBCC.nambaocao == nambaocao),\
                                                TienDoKeHoachBCC.tuyendonvi == 'thon').all()
    if records_thonxom is not None:
        for item_thonxom in records_thonxom:
            baocao_thonxom = to_dict(item_thonxom)
            if (item_thonxom.thonxom is not None):
                baocao_thonxom['xaphuong'] = to_dict(item_thonxom.thonxom)
            results.append(baocao_thonxom)
    else:
        results = []
    return results
async def postprocess_add_stt(request=None, Model=None, result=None, **kw):
    if result is not None and "objects" in result:
        objects = to_dict(result["objects"])
        datas = []
        i =1
        page = request.args.get("page",None)
        results_per_page = request.args.get("results_per_page",None)
        if page is not None and results_per_page is not None and int(page) != 1:
            i = i + int(results_per_page)*int(page)
        for obj in objects:
            if obj is not None:
                obj_tmp = to_dict(obj)
                obj_tmp["stt"] = i
                i = i +1
                datas.append(obj_tmp)
        result = datas
예제 #24
0
def user_to_dict(user):
    obj = to_dict(user)
    if "password" in obj:
        del (obj["password"])
    if "salt" in obj:
        del (obj["salt"])
    return obj
예제 #25
0
async def send_notify_multiple(list_user_id, title, content, id_datkham):
    if(title is None or title == ""):
        title = "Thông báo đặt khám"
    notify_record = Notify()
    notify_record.title = title
    notify_record.content = content
    notify_record.type = "text"
    notify_record.action = {"datkham_id":str(id_datkham)}
    db.session.add(notify_record)
    db.session.flush()
    notify_record.url = app.config.get("DOMAIN_URL") + "/#dangkykham/model?id="+str(id_datkham)
    notify_user_list = []
    for uid in list_user_id:
        notify_user = NotifyUser()
        notify_user.user_id = uid
        notify_user.notify_id = notify_record.id
        notify_user.notify_at = floor(time.time())
        db.session.add(notify_user)
    
        # notify user
        user_notify_token = redisdb.get("notify_token:" + str(uid))
        if user_notify_token is not None:
            user_notify_token = user_notify_token.decode('utf8')
            notify_user_list.append(user_notify_token)
    db.session.commit()
    await send_firebase_notify(notify_user_list, title, to_dict(notify_record))
예제 #26
0
async def check_exist_danhmuc(request=None, data=None, Model=None, **kw):
    if data is not None and "ma" in data and data[
            "ma"] is not None and isxaphuong == True:
        record = db.session.query(Model).filter(Model.ma == data['ma']).first()
        if record is not None:
            data['id'] = record.id
            return json(to_dict(record))
예제 #27
0
async def DonVitree(request):
    currentuser = await current_user(request)
    if currentuser is None:
        return json(
            {
                "error_code": "SESSION_EXPIRED",
                "error_message": "Hết phiên hoạt động, vui lòng đăng nhập lại"
            },
            status=520)

    is_admin = await hasRole(request, "Admin")
    data = None
    if (is_admin == True):
        data = db.session.query(DonVi).\
            options(joinedload_all("children", "children",
                "children", "children")).\
            filter(DonVi.id == currentuser.donvi_id).\
            first()
    else:
        data = db.session.query(DonVi).\
            options(joinedload_all("children", "children", "children", "children")).\
            join(TuyenDonVi, DonVi.tuyendonvi).filter(TuyenDonVi.ma == 'TW').first()

    if data is not None:
        obj = data.dump()
        return json(to_dict(obj))
    else:
        return json({})
예제 #28
0
async def send_notify_multiple(user_id, title, content, record_type, action,
                               id_url):
    # type_action
    if (title is None or title == ""):
        title = "Thông báo"
    notify_record = Notify()
    notify_record.title = title
    notify_record.content = content
    notify_record.type = record_type
    notify_record.action = None
    notify_record.url = record_type + "/model?id=" + str(id_url)
    db.session.add(notify_record)
    db.session.flush()
    list_key = []
    for key in redisdb_firebase.scan_iter():
        for _ in user_id:
            parseKey = key.decode("utf8")
            if parseKey == _:
                print("================", parseKey)
                list_key.append(redisdb_firebase.get(key).decode("utf8"))
    print("list_key", list_key)
    if list_key is not None:
        for _ in user_id:
            notify_user = NotifyUser()
            notify_user.user_id = _
            notify_user.notify_id = notify_record.id
            notify_user.notify_at = floor(time.time())
            notify_user.read_at = None
            db.session.add(notify_user)
            db.session.commit()
        await send_firebase_notify(list_key, title, to_dict(notify_record))
        return json({"ok": True, "message": "Send success"})
예제 #29
0
async def get_room_available(request):
    current_tenant = get_current_tenant(request)
    if current_tenant is None or 'error_code' in current_tenant:
        return json(
            {
                'error_code': 'TENANT_UNKNOWN',
                'error_message': 'Thông tin request không xác định'
            },
            status=523)

    tenant_id = current_tenant.get('id')
    now_time = now_timestamp()
    list_room_busy_ids = db.session.query(ContactRoomSession.room_id).filter(
        ContactRoomSession.end_time >= now_time,
        ContactRoomSession.checkout == True,
        ContactRoomSession.tenant_id == tenant_id,
    ).distinct(ContactRoomSession.room_id).all()

    rooms_availabel = db.session.query(Room).filter(
        Room.active == True, ~Room.id.in_(list_room_busy_ids)).all()

    results = []
    for room in rooms_availabel:
        results.append(to_dict(room))
    return json({'results': results}, status=200)
예제 #30
0
async def get_user_with_permission(user):
    user_info = to_dict(user)
    roles = [{
        "id": str(role.id),
        "description": role.description,
        "role_name": role.name
    } for role in user.roles]
    roleids = [role.id for role in user.roles]
    print("roles====", roles)
    user_info["roles"] = roles

    #permission:
    #     perms = Permission.query.filter(Permission.role_id.in_(roleids)).order_by(Permission.subject).all()
    #     permobj = {}
    #
    #     for perm in perms:
    #         if perm.subject not in permobj:
    #             permobj[perm.subject] = {}
    #
    #         if perm.permission not in permobj[perm.subject]:
    #             permobj[perm.subject][perm.permission] = perm.value
    #         elif not permobj[perm.subject][perm.permission]:
    #             permobj[perm.subject][perm.permission] = perm.value
    #     user_info["permission"] = permobj
    exclude_attr = ["password",  "created_at", "created_by", "updated_at", "updated_by",\
                        "deleted_by", "deleted_at", "deleted","salt","active","phone_country_prefix","phone_national_number"]

    for attr in exclude_attr:
        if attr in user_info:
            del (user_info[attr])
    return user_info