Ejemplo n.º 1
0
    def update_user(self):
        ## post with json
        #{
        #   "rid": xx,
        #   "action": "update_user",
        #   "user":
        #      {
        #         "name": XX,
        #         "icon_base64":
        #         "me": xx
        if not request.is_json:
            return self.response_400(message="Request payload is not JSON")

        user = request.json.get('user', None)
        rid = request.json.get('rid', None)

        if not user or not rid:
            return self.response_400(message="Missing required parameter")

        s = self.datamodel.session
        _datamodel = SQLAInterface(ProjectFiles)
        _datamodel.session = s
        filters = _datamodel.get_filters()
        filters.add_filter('name', FilterEqual, str(rid))
        count, item = _datamodel.query(filters=filters, page_size=1)

        if count is 0:
            return self.response_400(message=("Missing required parameter, rid %s" % rid))

        item = item[0]
        item.user_name = user['name']
        item.icon_base64 = user['icon_base64']
        item.me_id = user['me_id']

        _datamodel.add(item)

        message = "warning"

        try:
            s.commit()
            message = "success"
        except IntegrityError as e:
            message = "warning"
            log.warning(LOGMSG_WAR_DBI_ADD_INTEGRITY.format(str(e)))
            s.rollback()
            if raise_exception:
                raise e
        except Exception as e:
            message = str(sys.exc_info()[0]) + "danger"
            log.exception(LOGMSG_ERR_DBI_ADD_GENERIC.format(str(e)))
            s.rollback()
            if raise_exception:
                raise e

        return self.response(200, message=message)
Ejemplo n.º 2
0
    def logout(self, name=-1):
        resp = {
            'status': 1,
            'msg': ''
        }
        if request.method == 'POST':
            if name and name != -1:
                line_id = name
            else:
                line_id = get_line_id_by_current_user(self.datamodel.session)
            socketio.emit('message', {
                'action': 'logout',
                'p': ''
            },
                          namespace='/canary',
                          room=name)
            resp = {
                'status': 0,
                'msg': 'logout success'
            }

            _datamodel = SQLAInterface(ProjectFiles, self.datamodel.session)
            filters = _datamodel.get_filters()
            filters.add_filter('name', FilterEqual, name)
            count, item = _datamodel.query(filters=filters)
            for i in item:
                #g['is_logout'][name] = -2
                i.status = -2
                _datamodel.add(i)

                global g
                g['status'][i.me_id][name]['status'] = -1

            #return redirect(self.route_base)

        widgets = self._list()
        return self.render_template('line_function.html',
                                    title=self.list_title,
                                    widgets=widgets,
                                    is_logout=True,
                                    resp=resp)
Ejemplo n.º 3
0
def resp_heartbeat(rid, is_alive, is_socket_emit=True):
    global g
    #print('received my event: ' + str(json) + json['action'])
    _datamodel = SQLAInterface(ProjectFiles, db.session)
    filters = _datamodel.get_filters()
    filters.add_filter('name', FilterEqual, rid)
    count, item = _datamodel.query(filters=filters,
                                   order_column='id',
                                   order_direction='desc',
                                   page_size=-1)
    item = item[0]
    item.status = is_alive
    _datamodel.add(item)

    try:
        db.session.commit()
    except IntegrityError as e:
        db.session.rollback()
        if raise_exception:
            raise e
    except Exception as e:
        db.session.rollback()
        if raise_exception:
            raise e

    if item.status is 1:
        g['is_logout'][rid] = 0

        if is_socket_emit:
            print('emit add friend %s from %s' % (item.description, item.name))
            socketio.emit('message', {
                'action': 'add_friend',
                'p': item.description
            },
                          namespace='/canary',
                          room=item.name)
        else:
            return item.description

    return ""
Ejemplo n.º 4
0
    def _store(self, pk, values):
        from uniset.models import UserProfile
        from superset import db
        from flask_appbuilder.security.sqla.models import User

        created = False
        datamodel = SQLAInterface(User, db.session)

        P = SQLAInterface(UserProfile, db.session)
        u = db.session.query(User).filter_by(email=values['email']).first()
        if not u:
            created = True
            u = User(first_name=values['first_name'],
                     last_name=values['last_name'],
                     email=values['email'],
                     username=values['email'],
                     roles=[self.extra['role']],
                     active=False)
            datamodel.add(u)
        else:
            datamodel.add(u)
        if u.profiles:
            profile = u.profiles[0]
            profile.uuid = values['azure_id']
        else:
            profile = UserProfile(user_id=u.id)
            profile.uuid = values['azure_id']
        P.add(profile)
        return values, created
Ejemplo n.º 5
0
def old_codes_update(self, file):
    book = openpyxl.load_workbook(file)
    sheet = book.active
    #header = sheet['A1':'M1']
    '''
    unit = header[0][0].value
    materialclass = header[0][1].value
    doctype = header[0][2].value
    bapco_code = header[0][5].value
    description = header[0][6].value
    oldcode = header[0][7].value
    cdrlitem = header[0][8].value
    documentclass =header[0][9].value
    note = header[0][10].value
    trasmittal = header[0][11].value
    '''
    session = db.session
    datamodel = SQLAInterface(DocRequests, session=session)

    for row in sheet.iter_rows(min_row=2):
        req = DocRequests()
        req.quantity = 1
        req.unit = Unit(unit=row[0].value)
        req.materialclass = Materialclass(materialclass=row[1].value)
        req.doctype = Doctype(doctype=row[2].value)
        req.cdrlitem = Cdrlitem(cdrlitem=row[8].value)
        req.documentclass = Documentclass(documentclass=row[9].value)
        req.partner = Partner(partner=row[12].value)
        #req.oldcode = row[7].value
        print('search for Unit:', req.unit.unit)
        #code = bapco(self, req)
        #row[14] = code
        datamodel.add(req)

    reserved_list = ['coming soon...']
    updated_list = ['coming soon...']
    book.close()
    return reserved_list, updated_list
Ejemplo n.º 6
0
def setting_update(file):
    session = db.session
    print('Setting Update start')
    book = openpyxl.load_workbook(file)
    sheet = book.active
    set_class = sheet['A1'].value
    print('the setting class:', set_class)

    reserved_list = []
    updated_list = []

    for row in sheet.iter_rows(min_row=2):
        param = row[0].value
        name = row[1].value
        desc = row[2].value
        print(param, name, desc)
        set_dict = {
            'Job': [Job, Job.job],
            'Discipline': [Discipline, Discipline.discipline],
            'Unit': [Unit, Unit.unit],
            'Application': [Application, Application.application],
            'Doctype': [Doctype, Doctype.doctype],
            'Subdoctype': [Subdoctype, Subdoctype.subdoctype],
            'Domain': [Domain, Domain.domain],
            'Cdrlitem': [Cdrlitem, Cdrlitem.cdrlitem],
            'Documentclass': [Documentclass, Documentclass.documentclass],
            'Mr': [Mr, Mr.mr],
            'Vendor': [Vendor, Vendor.vendor],
            'Partner': [Partner, Partner.partner]
        }
        # Update the setting if a param already exist
        tmp_class = set_dict[set_class][0]
        tmp_param = set_dict[set_class][1]
        my_class = db.session.query(tmp_class).filter(
            tmp_param == str(param)).first()

        datamodel = SQLAInterface(tmp_class, session=session)

        if my_class:
            print(my_class)
            my_class.name = name
            my_class.description = desc
            datamodel.edit(my_class)
            updated_list.append(
                [my_class.id, my_class.name, my_class.description])
        else:
            # or Create new record in setting

            my_class = tmp_class()
            if set_class == 'Unit':
                my_class.unit = param
            elif set_class == 'Job':
                my_class.job = param
            elif set_class == 'Discipline':
                my_class.discipline = param
            elif set_class == 'Application':
                my_class.application = param
            elif set_class == 'Doctype':
                my_class.doctype = param
            elif set_class == 'Subdoctype':
                my_class.subdoctype = param
            elif set_class == 'Domain':
                my_class.domain = param
            elif set_class == 'Cdrlitem':
                my_class.cdrlitem = param
            elif set_class == 'Documentclass':
                my_class.documentclass = param
            elif set_class == 'Mr':
                my_class.mr = param
            elif set_class == 'Vendor':
                my_class.vendor = param
            elif set_class == 'Partner':
                my_class.partner = param

            else:
                return print('Setting Class NOT Found')

            my_class.name = name
            my_class.description = desc
            datamodel.add(my_class)
            reserved_list.append(
                [my_class.id, my_class.name, my_class.description])

    return reserved_list, updated_list
Ejemplo n.º 7
0
def init_bapco(self, item):
    # Set the DB session
    session = db.session

    id_unit = db.session.query(Unit).filter(
        Unit.id == str(item.unit_id)).first()
    print('id_unit ', id_unit)
    id_materialclass = db.session.query(Materialclass).filter(
        Materialclass.id == str(item.materialclass_id)).first()
    id_doctype = db.session.query(Doctype).filter(
        Doctype.id == str(item.doctype_id)).first()
    id_patner = db.session.query(Partner).filter(
        Partner.id == str(item.partner_id)).first()
    id_cdrlitem = None
    id_documentclass = None
    id_vendor = None
    id_mr = None

    req = DocRequests(unit_id=id_unit.id,
                      materialclass_id=id_materialclass.id,
                      doctype_id=id_doctype.id,
                      partner_id=id_patner.id,
                      request_type=item.request_type)

    doc = Document(unit_id=id_unit.id,
                   materialclass_id=id_materialclass.id,
                   doctype_id=id_doctype.id,
                   partner_id=id_patner.id)

    if item.cdrlitem_id:
        id_cdrlitem = db.session.query(Cdrlitem).filter(
            Cdrlitem.id == str(item.cdrlitem_id)).first()
        req.cdrlitem_id = id_cdrlitem.id
        doc.cdrlitem_id = id_cdrlitem.id

    if item.documentclass_id:
        id_documentclass = db.session.query(Documentclass).filter(
            Documentclass.id == str(item.documentclass_id)).first()
        req.documentclass_id = id_documentclass.id
        doc.documentclass_id = id_documentclass.id

    # Set the Request type
    if item.vendor and item.mr:
        req.request_type = 'vendor'
        id_vendor = db.session.query(Vendor).filter(
            Vendor.id == str(item.vendor_id)).first()
        id_mr = db.session.query(Mr).filter(Mr.id == str(item.mr_id)).first()
        req.vendor_id = id_vendor.id
        req.mr_id = id_mr.id

        doc.vendor_id = id_vendor.id
        doc.mr_id = id_mr.id

    else:
        req.request_type = 'engineering'

    # Set item_matrix based on unit type
    result = db.session.query(Unit).filter(
        Unit.id == str(item.unit_id)).first()

    if str(result.unit_type) == 'common':
        print('Match unit type common Found')

        # Add the partner id to the matrix
        item_matrix = str.join(
            '-',
            (
                str(id_unit.unit),
                str(id_materialclass.materialclass),
                str(id_doctype.doctype),
                # item.sheet,
                str(id_patner.partner)))
    else:
        item_matrix = str.join(
            '-',
            (
                str(id_unit.unit),
                str(id_materialclass.materialclass),
                str(id_doctype.doctype),
                # item.sheet,
            ))
    # Set the bapco base code
    item_serial = str.join(
        '-',
        (
            str(id_unit.unit),
            str(id_materialclass.materialclass),
            str(id_doctype.doctype),
            # item.sheet,
        ))

    # Increment the Matrix counter or create a new one
    print(
        'Matrix to search:',
        (
            str(id_unit.unit),
            str(id_materialclass.materialclass),
            str(id_doctype.doctype),
            # item.sheet,
            str(id_patner.partner)))
    matrix = db.session.query(Matrix).filter(
        Matrix.matrix == item_matrix).first()
    if matrix:
        matrix.counter += 1
        datamodel = SQLAInterface(Matrix, session=session)
        datamodel.edit(matrix)

        req.matrix_id = matrix.id
        code = item_serial + "-" + str(
            matrix.counter).zfill(5) + "-" + item.sheet

        datamodel = SQLAInterface(Document, session=session)

        #doc = Document(docrequests=req, code=code)
        doc.docrequests = req
        doc.code = code
        datamodel.add(doc)

        message = 'Your code is ' + code
        flash(message, category='info')
    else:
        # Create a New Matrix for common units
        if result.unit_type == 'common':

            print('item partner to find: ', id_patner.partner)

            partner = db.session.query(Partner).filter(
                Partner.id == str(item.partner_id)).first()

            matrix = Matrix(counter=partner.common_start + 1,
                            matrix=str(item_matrix))
            datamodel = SQLAInterface(Matrix, session=session)
            datamodel.add(matrix)

            # Find the Matrix'ID
            id_matrix = db.session.query(Matrix).filter(
                Matrix.matrix == item_matrix).first()
            req.matrix_id = id_matrix.id

            # Add new Doc with quantity partner common start + 1

            code = item_serial + "-" + str(partner.common_start +
                                           1).zfill(5) + "-" + item.sheet

            datamodel = SQLAInterface(Document, session=session)

            #doc = Document(docrequests=req, code=code)
            doc.docrequests = req
            doc.code = code

            datamodel.add(doc)

            message = 'Your code is ' + code
            flash(message, category='info')
        else:
            # Create a new Matrix for standard units
            datamodel = SQLAInterface(Matrix, session=session)
            matrix = Matrix(matrix=item_matrix)
            datamodel.add(matrix)

            # Find the Matrix'ID
            id_matrix = db.session.query(Matrix).filter(
                Matrix.matrix == item_matrix).first()
            req.matrix_id = id_matrix.id

            # Add new Doc with quantity 1

            code = item_serial + "-" + "1".zfill(5) + "-" + item.sheet

            datamodel = SQLAInterface(Document, session=session)

            #doc = Document(docrequests=req, code=code)
            doc.docrequests = req
            doc.code = code

            datamodel.add(doc)

            message = 'Your code is ' + code
            flash(message, category='info')

    db.session.flush()
    return code
Ejemplo n.º 8
0
def adddoc3(self, item):
    # Set the Request type
    if item.vendor and item.mr:
        item.request_type = 'vendor'

    session = db.session
    matrix = session.query(Matrix)
    if item.unit.unit == '000':
        item_matrix = str.join(
            '-',
            (
                item.unit.unit,
                item.materialclass.materialclass,
                item.doctype.doctype,
                # item.sheet,
                item.partner.partner))
    else:
        item_matrix = str.join(
            '-',
            (
                item.unit.unit,
                item.materialclass.materialclass,
                item.doctype.doctype,
                # item.sheet,
            ))

    item_serial = str.join(
        '-',
        (
            item.unit.unit,
            item.materialclass.materialclass,
            item.doctype.doctype,
            # item.sheet,
        ))

    print('controllo item_ matrix', item_matrix)
    found = False
    for row in matrix:
        print('loop controllo matrix uguali', row.matrix, item_matrix,
              item.matrix)
        if row.matrix == item_matrix:
            print('trovate matrix uguali')
            print('row counter prima:', row.counter)
            row.counter += 1
            print('row counter dopo:', row.counter)
            datamodel = SQLAInterface(Matrix, session=session)
            datamodel.edit(row)

            item.matrix_id = row.id
            code = item_serial + "-" + str(
                row.counter).zfill(5) + "-" + item.sheet

            datamodel = SQLAInterface(Document, session=session)
            doc = Document(docrequests_id=item.id, code=code)
            datamodel.add(doc)

            message = 'Your code is ' + code
            flash(message, category='info')
            found = True

    # Matrix Not Found
    if found is False:
        print('Matrix NOT FOUND')

        if str(item.unit) == '000':
            print('found unit 000')
            jv = {'TTSJV': 50000, 'TPIT': 60000}

            # Add New Matrix
            datamodel = SQLAInterface(Matrix, session=session)

            print('counter', jv['TTSJV'], item.partner, jv[str(item.partner)])
            print('item matrix:', item_matrix)

            matrix = Matrix(counter=jv[str(item.partner)] + 1,
                            matrix=item_matrix)

            print('-----2------')

            datamodel.add(matrix)

            # Add New Doc with quantity jv + 1
            datamodel = SQLAInterface(Document, session=session)
            code = item_serial + "-" + str(jv[str(item.partner)] +
                                           1).zfill(5) + "-" + item.sheet
            doc = Document(docrequests_id=item.id, code=code)

            datamodel.add(doc)
            message = 'Your code is ' + code
            flash(message, category='info')

        else:
            # Add New Matrix
            datamodel = SQLAInterface(Matrix, session=session)
            print('item matrix:', item_matrix)

            print('item matrix after:', item_matrix)
            matrix = Matrix(matrix=item_matrix)
            datamodel.add(matrix)

            # Add New Doc with quantity 1
            datamodel = SQLAInterface(Document, session=session)
            code = item_serial + "-" + "1".zfill(5) + "-" + item.sheet
            doc = Document(docrequests_id=item.id, code=code)

            datamodel.add(doc)
            message = 'Your code is ' + code
            flash(message, category='info')

    db.session.flush()
Ejemplo n.º 9
0
def bapco(self, item):
    # Set the DB session
    session = db.session

    # Set tehe Document item
    print('document setting', item.job_id, item.discipline_id, item.unit_id,
          item.application_id, item.doctype_id, item.subdoctype_id,
          item.domain_id)

    doc = Document(job_id=item.job_id,
                   discipline_id=item.discipline_id,
                   unit_id=item.unit_id,
                   application_id=item.application_id,
                   domain_id=item.domain_id,
                   doctype_id=item.doctype_id,
                   subdoctype_id=item.subdoctype_id,
                   partner_id=item.partner_id)

    print('document setted')
    if item.documentclass:
        print('documentclass', item.documentclass, item.documentclass_id)
        doc.documentclass_id = item.documentclass_id

    if item.cdrlitem:
        print('cdrlitem', item.cdrlitem, item.cdrlitem_id)
        doc.cdrlitem_id = item.cdrlitem_id

    # Set the Request type
    if item.vendor and item.mr:
        item.request_type = 'vendor'
        doc.vendor_id = item.vendor_id
        doc.mr_id = item.mr_id

    else:
        item.request_type = 'engineering'

    # Set item_matrix based on unit type
    print(item.unit.unit)
    result = db.session.query(Unit).filter(
        Unit.unit == str(item.unit.unit)).first()
    print("result", result)

    if str(result.unit_type) == 'common':
        print('Match unit type common Found')

        # Add the partner id to the matrix
        item_matrix = str.join(
            '-',
            (
                str(item.job.job),
                str(item.discipline.discipline),
                str(item.unit.unit) + str(item.application.application),
                str(item.doctype.doctype) + str(item.subdoctype.subdoctype),
                str(item.domain.domain),
                # item.sheet,
                str(item.partner)))

    else:

        item_matrix = str.join(
            '-', (str(item.job.job), str(item.discipline.discipline),
                  str(item.unit.unit) + str(item.application.application),
                  str(item.doctype.doctype) + str(item.subdoctype.subdoctype),
                  str(item.domain.domain)))
    # Set the bapco base code
    item_serial = str.join(
        '-',
        (
            str(item.job.job), str(item.discipline.discipline),
            str(item.unit.unit) + str(item.application.application),
            str(item.doctype.doctype) + str(item.subdoctype.subdoctype),
            str(item.domain.domain)
            # item.sheet,
        ))

    # Increment the Matrix counter or create a new one

    matrix = db.session.query(Matrix).filter(
        Matrix.matrix == item_matrix).first()
    partner = db.session.query(Partner).filter(
        Partner.partner == str(item.partner)).first()
    print('item_matrix, matrix', item_matrix, matrix)

    if matrix:
        print('matrix, counter', matrix, matrix.counter)

        if matrix.counter + 1 <= result.stop or matrix.counter + 1 <= partner.common_stop:
            print('matrix, counter', matrix, matrix.counter)
            #
            print('you are here')
            matrix.counter += 1
            datamodel = SQLAInterface(Matrix, session=session)
            datamodel.edit(matrix)

            item.matrix_id = matrix.id
            doc.matrix_id = matrix.id
            code = item_serial + str(matrix.counter).zfill(3)

            datamodel = SQLAInterface(Document, session=session)

            doc.docrequests_id = item.id
            doc.code = code

            datamodel.add(doc)

            message = 'Your code is ' + code
            flash(message, category='info')
        else:
            flash('No more Numbers available for this combination.',
                  category='warning')

    else:
        # Create a New Matrix for common units
        if result.unit_type == 'common':

            print('item partner to find: ', item.partner)

            partner = db.session.query(Partner).filter(
                Partner.partner == str(item.partner.partner)).first()

            matrix = Matrix(counter=partner.common_start + 1,
                            matrix=str(item_matrix))
            datamodel = SQLAInterface(Matrix, session=session)
            datamodel.add(matrix)

            matrix = db.session.query(Matrix).filter(
                Matrix.matrix == item_matrix).first()

            # Add new Doc with quantity partner common start + 1
            datamodel = SQLAInterface(Document, session=session)

            code = item_serial + str(partner.common_start + 1).zfill(3)

            #doc = Document(docrequests_id=item.id, code=code)
            doc.matrix_id = matrix.id
            doc.docrequests_id = item.id
            doc.code = code

            datamodel.add(doc)
            message = 'Your code is ' + code
            flash(message, category='info')

        else:
            # Create a new Matrix for standard units

            datamodel = SQLAInterface(Matrix, session=session)
            matrix = Matrix(counter=result.start + 1, matrix=item_matrix)
            datamodel.add(matrix)

            matrix = db.session.query(Matrix).filter(
                Matrix.matrix == item_matrix).first()

            # Add new Doc with quantity 1
            datamodel = SQLAInterface(Document, session=session)
            code = item_serial + str(result.start + 1).zfill(3)
            #doc = Document(docrequests_id=item.id, code=code)
            doc.matrix_id = matrix.id
            doc.docrequests_id = item.id
            doc.code = code

            datamodel.add(doc)
            message = 'Your code is ' + code
            flash(message, category='info')

    db.session.flush()
    return code
Ejemplo n.º 10
0
    def add(self):
        ## post with json
        if request.is_json:
            name = request.json.get('name', None)
            login_qrcode_base64 = request.json.get('login_qrcode_base64', None)
            description = request.json.get('description', None)

            if name is None or login_qrcode_base64 is None:
                return self.response_400(message="Request payload is not JSON")

            s = self.datamodel.session
            #datamodel = SQLAInterface(Project)
            #datamodel.session = s

            #filters = datamodel.get_filters()
            #filters.add_filter('name', FilterEqual, name)
            #count, item = datamodel.query(filters=filters, page_size=1)
            #if count:
            #    item = item[0]
            #    pid = item.id
            #    datamodel = SQLAInterface(ProjectFiles)
            #    datamodel.session = s
            #    filters = datamodel.get_filters()
            #    filters.add_filter('project_id', FilterEqual, pid)
            #    count, child = datamodel.query(filters=filters, page_size=1)
            #    child = child[0]

            #else:
            #    item = datamodel.obj()
            #    item.name = name
            #    item.created_by_fk = 1
            #    item.changed_by_fk = 1

            #    datamodel.add(item)

            #    pid = item.id

            #    datamodel = SQLAInterface(ProjectFiles)
            #    datamodel.session = s
            #    child = datamodel.obj()

            datamodel = SQLAInterface(ProjectFiles, s)

            filters = datamodel.get_filters()
            filters.add_filter('name', FilterEqual, name)
            count, item = datamodel.query(filters=filters, page_size=1)
            if count:
                child = item[0]
            else:
                child = datamodel.obj()

            child.name = name
            #child.description = description # description now is line_id for user's
            child.login_qrcode_base64 = login_qrcode_base64
            datamodel.add(child)

        else:
            name = request.form.get('name')

            if not name:
                return self.response_400(message="Missing required parameter")

            if 'file' not in request.files:
                flash('No file part')
                return self.response_400(message="Missing file parameter")
            file = request.files['file']

            if file.filename == '':
                return self.response_400(message="no file select")
            #filename = secure_filename(file.filename)
            #file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

            s = self.datamodel.session
            datamodel = SQLAInterface(Project)
            datamodel.session = s
            item = datamodel.obj()
            item.name = name
            item.created_by_fk = 1
            item.changed_by_fk = 1

            datamodel.add(item)
            pid = item.id

            im = ImageManager()
            filename = im.save_file(file, im.generate_name(file, file))

            datamodel = SQLAInterface(ProjectFiles)
            datamodel.session = s
            child = datamodel.obj()
            child.file = filename
            child.project = item
            child.description = request.form.get('description')
            datamodel.add(child)
        #datamodel._add_files(request, item)
        #log.warning("XX", item.id, "VV")

        return self.response(200, message=datamodel.message)
Ejemplo n.º 11
0
    def update_friend_icon(self):
        ## post with json
        #{
        #   "len":7,
        #   "rid": xx,
        #   "action": "update_friend_icon",
        #   "me_id":,
        #   "friends":
        #      {
        #         "xx":"xx",
        if not request.is_json:
            return self.response_400(message="Request payload is not JSON")

        friends_len = request.json.get('len', None)
        friends = request.json.get('friends', None)
        me_id = request.json.get('me_id', None)
        rid = request.json.get('rid', None)

        if not friends_len or not friends or not rid or not me_id:
            return self.response_400(message="Missing required parameter")

        s = self.datamodel.session
        _datamodel = SQLAInterface(ProjectFiles)
        _datamodel.session = s
        filters = _datamodel.get_filters()
        filters.add_filter('name', FilterEqual, str(rid))
        count, item = _datamodel.query(filters=filters, page_size=1)

        if count is 0:
            return self.response_400(message=("Missing required parameter, rid %s" % rid))

        uid = item[0].project.user_id

        for k in friends:
            _datamodel = SQLAInterface(Contact)
            _datamodel.session = s
            filters = _datamodel.get_filters()
            filters.add_filter('name', FilterEqual, rid)
            filters.add_filter('from_id', FilterEqual, k)
            filters.add_filter('me_id', FilterEqual, me_id)
            count, item = _datamodel.query(filters=filters, page_size=0)

            id = -1;
            if count:
                item = item[0]
                item.icon_base64 = friends[k]
                _datamodel.add(item)

        message = "warning"

        try:
            s.commit()
            message = "success"
        except IntegrityError as e:
            message = "warning"
            log.warning(LOGMSG_WAR_DBI_ADD_INTEGRITY.format(str(e)))
            s.rollback()
            if raise_exception:
                raise e
        except Exception as e:
            message = str(sys.exc_info()[0]) + "danger"
            log.exception(LOGMSG_ERR_DBI_ADD_GENERIC.format(str(e)))
            s.rollback()
            if raise_exception:
                raise e

        return self.response(200, message=message)
Ejemplo n.º 12
0
    def update_group(self):
        ## post with json
        #{
        #   "len":7,
        #   "rid": xx,
        #   "action": "update_group",
        #   "groups":[
        #      {  },
        #      {
        #         "id":"u4ddf1308a8747a3f815cb2959c068ebf",
        #         "name": XX,
        #         "icon_base64":
        #         "me_id":
        if not request.is_json:
            return self.response_400(message="Request payload is not JSON")

        group_len = request.json.get('len', None)
        groups = request.json.get('groups', None)
        rid = request.json.get('rid', None)

        if not group_len or not groups or not rid:
            return self.response_400(message="Missing required parameter")

        s = self.datamodel.session
        _datamodel = SQLAInterface(ProjectFiles)
        _datamodel.session = s
        filters = _datamodel.get_filters()
        filters.add_filter('name', FilterEqual, str(rid))
        count, item = _datamodel.query(filters=filters, page_size=1)

        if count is 0:
            return self.response_400(message=("Missing required parameter, rid %s" % rid))

        uid = item[0].project.user_id

        for cs in groups:
            if cs.get('id', None) is None:
                log.warning('id not found, current is', cs)
                continue

            _datamodel = SQLAInterface(ContactGroup)
            _datamodel.session = s
            filters = _datamodel.get_filters()
            filters.add_filter('line_id', FilterEqual, cs['id']) # to
            filters.add_filter('projectfiles_name', FilterEqual, rid)
            filters.add_filter('me_id', FilterEqual, cs['me_id'])
            filters.add_filter('user_id', FilterEqual, uid)
            count, item = _datamodel.query(filters=filters, page_size=0)

            id = -1;
            if count:
                group = item[0]
            else:
                group = ContactGroup()
                print("VVV", filters)

            group.line_id = cs['id'] # to
            group.projectfiles_name = rid
            group.user_id = uid
            group.name = cs['name']
            group.icon_base64 = cs['icon_base64']
            group.me_id  = cs['me_id']
            _datamodel.add(group)

        message = "warning"

        try:
            s.commit()
            message = "success"
        except IntegrityError as e:
            message = "warning"
            log.warning(LOGMSG_WAR_DBI_ADD_INTEGRITY.format(str(e)))
            s.rollback()
            if raise_exception:
                raise e
        except Exception as e:
            message = str(sys.exc_info()[0]) + "danger"
            log.exception(LOGMSG_ERR_DBI_ADD_GENERIC.format(str(e)))
            s.rollback()
            if raise_exception:
                raise e

        return self.response(200, message=message)
Ejemplo n.º 13
0
    def add_chats(self):
        ## post with json
        #{
        #   "len":7,
        #   "rid":,
        #   "chat":[
        #      {  },
        #      {  },
        #      {  },
        #      {
        #         "id":"u4ddf1308a8747a3f815cb2959c068ebf",
        #         "me_id": xxx
        #         "icon_base64": xxx,
        #         "title":[
        #            "5/6/2019,周小艾,9:21 PM"
        #         ],
        #         "chat":[
        #            {
        #               "title":"周小艾",
        #               "chat":"五次",
        #               "t":"9:21 PM",
        #               "time":1559740894260
        #               "icon_base64":
        #            },
        if not request.is_json:
            return self.response_400(message="Request payload is not JSON")
        chat_len = request.json.get('len', None)
        chats = request.json.get('chat', None)
        rid = request.json.get('rid', None)

        if not chat_len or not chats or not rid:
            return self.response_400(message="Missing required parameter")

        s = self.datamodel.session

        #_datamodel = SQLAInterface(Project)
        _datamodel = SQLAInterface(ProjectFiles)
        _datamodel.session = s
        filters = _datamodel.get_filters()
        filters.add_filter('name', FilterEqual, str(rid))
        count, item = _datamodel.query(filters=filters, page_size=1)

        if count is 0:
            return self.response_400(message=("Missing required parameter, rid %s" % rid))

        uid = item[0].project.user_id

        need_commit = 0
        for cs in chats:
            if cs.get('id', None) is None:
                log.warning('id not found, current is', cs)
                continue

            _datamodel = SQLAInterface(ContactGroup)
            _datamodel.session = s
            filters = _datamodel.get_filters()
            filters.add_filter('line_id', FilterEqual, cs['id']) # to
            filters.add_filter('projectfiles_name', FilterEqual, rid)
            filters.add_filter('me_id', FilterEqual, cs['me_id'])
            filters.add_filter('user_id', FilterEqual, uid)
            #count = 0
            count, item = _datamodel.query(filters=filters, page_size=0)
            #item = _datamodel._get_base_query(s.query(_datamodel.obj), filters=filters).first()
            #if item:
            #    item = [item]

            id = -1;
            if count:
                group = item[0]
                id = group.id
            else:
                group = ContactGroup()
                group.line_id = cs['id']
                group.projectfiles_name = rid
                group.name = cs['title']
                group.me_id = cs['me_id']
                group.user_id = uid
                group.icon_base64 = cs.get('icon_base64', cs['chat'][0]['icon_base64'])
                _datamodel.add(group)
                id = group.id

            is_updated = False
            latest_update = None

            for c in cs['chat']:
                _datamodel = SQLAInterface(Contact)
                _datamodel.session = s
                filters = _datamodel.get_filters()
                filters.add_filter('updated', FilterEqual, datetime.datetime.fromtimestamp(int(c['time']) / 1000))
                filters.add_filter('contact_group_id', FilterEqual, id)
                filters.add_filter('line_id', FilterEqual, cs['id']) # to
                filters.add_filter('from_id', FilterEqual, c['from'])
                filters.add_filter('me_id', FilterEqual, cs['me_id']) # could remove?
                #count, item = _datamodel.query(filters=filters, page_size=0)
                #item = _datamodel._get_base_query(s.query(_datamodel.obj), filters=filters).first()
                item = None
                is_found = False

                if c['from_display_name'] == "" or c['icon_base64'] == "":
                    print("no diaplay name and icon base")
                    #print("no diaplay name and icon base", str(c))
                    continue

                #item = _datamodel._get_base_query(s.query(_datamodel.obj), filters=filters).limit(1).first()
                #if item:
                #    item = [item]
                #    is_found = True
                ##if len(item) > 0:
                ##    for i in item:
                ##        if i.contact_group_id == id and i.line_id == cs['id'] and i.from_id == c['from'] and i.me_id == cs['me_id']:
                ##            is_found = True
                ##            item[0] = i
                ##            break

                if is_found:
                    # update 
                    is_dirty = False
                    item = item[0]
                    if item.from_display_name == "" and c['from_display_name'] != "":
                        item.from_display_name = c['from_display_name']
                        is_dirty = True

                    if item.icon_base64 == "" and c['icon_base64'] != "":
                        item.icon_base64 = c['icon_base64']
                        is_dirty = True

                    if is_dirty:
                        need_commit += 1
                        s.add(item)

                else:
                    is_updated = True
                    item = Contact()
                    #d = datetime()
                    #d = datetime.datetime.fromtimestamp
                    item.name = c['title'] 
                    item.msg = c['chat'] 
                    t = int(c['time']) / 1000
                    item.updated = datetime.datetime.fromtimestamp(t)
                    if latest_update:
                        if item.updated > latest_update:
                            latest_update = item.updated 
                    else:
                        latest_update = item.updated

                    item.line_id = cs['id']
                    #item.t = c['t']
                    item.user_id = uid
                    item.contact_group_id = id
                    item.from_display_name = c['from_display_name']
                    item.me_id =  cs['me_id']
                    item.from_id = c['from']
                    item.icon_base64 = c['icon_base64']
                    item.c_type= c.get('type', 1)

                    need_commit += 1
                    s.add(item)

            if is_updated:
                if group.updated is None or latest_update > group.updated:
                    group.updated = latest_update 
                    s.add(group)


        if need_commit is 0:
            return self.response(200, message="no one update")

        message = "warning"
        try:
            s.commit()
            message = "success"
        except IntegrityError as e:
            message = "warning"
            log.warning(LOGMSG_WAR_DBI_ADD_INTEGRITY.format(str(e)))
            s.rollback()
            if raise_exception:
                raise e
        except Exception as e:
            message = str(sys.exc_info()[0]) + "danger"
            log.exception(LOGMSG_ERR_DBI_ADD_GENERIC.format(str(e)))
            s.rollback()
            if raise_exception:
                raise e

        return self.response(200, message=message)
Ejemplo n.º 14
0
def bapco(self, item):
    # Set the DB session
    session = db.session

    # Set the Request type
    if item.vendor and item.mr:
        item.request_type = 'vendor'
    else:
        item.request_type = 'engineering'

    # Set item_matrix based on unit type
    result = db.session.query(Unit).filter(Unit.unit == str(item.unit)).first()

    if str(result.unit_type) == 'common':
        print('Match unit type common Found')

        # Add the partner id to the matrix
        item_matrix = str.join(
            '-',
            (
                item.unit.unit,
                item.materialclass.materialclass,
                item.doctype.doctype,
                # item.sheet,
                item.partner.partner))
    else:
        item_matrix = str.join(
            '-',
            (
                item.unit.unit,
                item.materialclass.materialclass,
                item.doctype.doctype,
                # item.sheet,
            ))
    # Set the bapco base code
    item_serial = str.join(
        '-',
        (
            item.unit.unit,
            item.materialclass.materialclass,
            item.doctype.doctype,
            # item.sheet,
        ))

    # Increment the Matrix counter or create a new one
    matrix = db.session.query(Matrix).filter(
        Matrix.matrix == item_matrix).first()
    if matrix:
        matrix.counter += 1
        datamodel = SQLAInterface(Matrix, session=session)
        datamodel.edit(matrix)

        item.matrix_id = matrix.id
        code = item_serial + "-" + str(
            matrix.counter).zfill(5) + "-" + item.sheet

        datamodel = SQLAInterface(Document, session=session)
        doc = Document(docrequests_id=item.id, code=code)
        datamodel.add(doc)

        message = 'Your code is ' + code
        flash(message, category='info')
    else:
        # Create a New Matrix for common units
        if result.unit_type == 'common':

            partner = db.session.query(Partner).filter(
                Partner.partner == str(item.partner)).first()

            matrix = Matrix(counter=partner.common_start + 1,
                            matrix=str(item_matrix))
            datamodel = SQLAInterface(Matrix, session=session)
            datamodel.add(matrix)

            # Add new Doc with quantity partner common start + 1
            datamodel = SQLAInterface(Document, session=session)
            code = item_serial + "-" + str(partner.common_start +
                                           1).zfill(5) + "-" + item.sheet
            doc = Document(docrequests_id=item.id, code=code)
            datamodel.add(doc)
            message = 'Your code is ' + code
            flash(message, category='info')
        else:
            # Create a new Matrix for standard units
            datamodel = SQLAInterface(Matrix, session=session)
            matrix = Matrix(matrix=item_matrix)
            datamodel.add(matrix)

            # Add new Doc with quantity 1
            datamodel = SQLAInterface(Document, session=session)
            code = item_serial + "-" + "1".zfill(5) + "-" + item.sheet
            doc = Document(docrequests_id=item.id, code=code)

            datamodel.add(doc)
            message = 'Your code is ' + code
            flash(message, category='info')

    db.session.flush()
    return code
Ejemplo n.º 15
0
    def list(self):
        filters = self.datamodel.get_filters()
        filters.add_filter('user_id', FilterEqual, current_user.id)
        count, item = self.datamodel.query(filters=filters, page_size=1)
        ppk = -1
        limit_qrcode = -1
        if count:
            first_unused = item[0]
            ppk = first_unused.id
            limit_qrcode = first_unused.limit_qrcode
        else:
            item = self.datamodel.obj()
            item.created_by_fk = 1
            item.changed_by_fk = 1
            self.datamodel.add(item)
            ppk = item.id
            limit_qrcode = item.limit_qrcode

        _datamodel = SQLAInterface(ProjectFiles, self.datamodel.session)
        filters = _datamodel.get_filters()
        filters.add_filter('project_id', FilterEqual, ppk)
        count, item = _datamodel.query(filters=filters,
                                       order_column='id',
                                       order_direction='desc',
                                       page_size=-1)

        if count < limit_qrcode:
            filters.clear_filters()
            filters.add_filter('project_id', FilterEqual, None)
            _count, item = _datamodel.query(filters=filters, page_size=-1)
            for i in range(count, limit_qrcode):
                j = i - count
                item[j].project_id = ppk
                _datamodel.add(item[j])

        elif count > limit_qrcode:
            for i in range(limit_qrcode, count):
                j = i - limit_qrcode
                item[j].project_id = -1
                _datamodel.add(item[j])

        _datamodel = SQLAInterface(ProjectFiles, self.datamodel.session)
        filters = _datamodel.get_filters()
        filters.add_filter('project_id', FilterEqual, ppk)
        count, item = _datamodel.query(filters=filters,
                                       order_column='id',
                                       order_direction='desc',
                                       page_size=-1)
        for i in item:
            i.status = 0
            _datamodel.add(i)
            if i.name:
                socketio.emit('message', {
                    'action': 'heartbeat',
                    'p': ''
                },
                              namespace='/canary',
                              room=i.name)

        #self._base_filters = Project.is_used.is_(False)
        self._base_filters.clear_filters()
        self._base_filters.add_filter('user_id', FilterEqual, current_user.id)
        widgets = self._list()
        #show_template = "quickfiles.html"
        return self.render_template(
            self.list_template,
            title=self.list_title,
            widgets=widgets,
            #related_views=self._related_views,
        )