Пример #1
0
def save_data(model, did=None, **kwargs):
    kwargs = convert4datastore(kwargs)

    try:
        with session_scope() as session:
            if did:
                update_record(session, model, did, **kwargs)
            else:
                insert_or_ignore(session, model, **kwargs)

    except IntegrityError as e:
        mlogger.error(f'DB IntegrityError while saving {model.__name__} '
                      f'record with parameters {kwargs}')
        raise BabelError(e)
Пример #2
0
def copy_distribution_data(distr_record, user_id):

    try:
        with session_scope() as session:
            # create new name
            # check if used and adjust
            exists = True
            n = 0
            while exists:
                new_name = f'{distr_record.name}-copy({n})'
                rec = retrieve_record(
                    session, DistSet,
                    name=new_name,
                    user_id=user_id,
                    system_id=distr_record.system_id)
                if not rec:
                    exists = False
                n += 1

            # prep copy of distrgrids & gridlocations
            grids = []
            for grid in distr_record.distgrids:
                locs = []
                for loc in grid.gridlocations:
                    locs.append(
                        GridLocation(
                            branch_id=loc.branch_id,
                            shelfcode_id=loc.shelfcode_id,
                            qty=loc.qty))
                grids.append(
                    DistGrid(
                        name=grid.name,
                        gridlocations=locs))

            rec = insert(
                session,
                DistSet,
                name=new_name,
                system_id=distr_record.system_id,
                user_id=user_id,
                distgrids=grids)

            mlogger.debug(f'Added new record: {rec}')
    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error(
            'Unhandled error in copy distribution.'
            f'Traceback: {tb}')
        raise BabelError(exc)
Пример #3
0
def delete_data(record):
    try:
        # check if can be deteled without consequences first

        with session_scope() as session:
            model = type(record)
            delete_record(session, model, did=record.did)
        mlogger.debug('Deleted {} record did={}'.format(
            model.__name__, record.did))

    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error('Unhandled error cart deletion.' f'Traceback: {tb}')
        raise BabelError(exc)
Пример #4
0
def save_displayed_order_data(tracker_values):
    try:
        with session_scope() as session:
            for v in tracker_values:
                order = v['order']
                locs = v['grid']['locs']

                okwargs = {}
                locations = []
                for l in locs:
                    mlogger.debug('Saving orderLoc data: order_id:{}, '
                                  'loc_id:{}, frm_id:{}'.format(
                                      order['order_id'], l['loc_id'],
                                      l['unitFrm'].winfo_id()))
                    lkwargs = {}
                    if l['loc_id'] is not None:
                        lkwargs['did'] = l['loc_id']
                    if l['branchCbx'].get() != '':
                        rec_id = get_branch_rec_id(session,
                                                   l['branchCbx'].get())
                        lkwargs['branch_id'] = rec_id
                    if l['shelfCbx'].get() != '':
                        rec_id = get_shelf_rec_id(session, l['shelfCbx'].get())
                        lkwargs['shelfcode_id'] = rec_id
                    if l['qtyEnt'].get() != '':
                        lkwargs['qty'] = int(l['qtyEnt'].get())
                    if l['fundCbx'].get() != '':
                        rec_id = get_fund_rec_id(session, l['fundCbx'].get())
                        lkwargs['fund_id'] = rec_id
                        # validate here
                    if lkwargs:
                        locations.append(OrderLocation(**lkwargs))
                        mlogger.debug(
                            'Saving orderLoc data, params: {}'.format(lkwargs))

                okwargs = get_ids_for_order_boxes_values(order)
                okwargs['locations'] = locations
                mlogger.debug('Saving order data (id:{}), params: {}'.format(
                    order['order_id'], okwargs))

                update_record(session, Order, order['order_id'], **okwargs)

    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error('Unhandled error on saving cart data.'
                      f'Traceback: {tb}')
        raise BabelError(exc)
Пример #5
0
def update_fund(**kwargs):
    """
    Adds a new fund with all related data
    args:
        system_id: int, datastore did of NYPL or BPL
        fund_code: str, Sierra fund code
        describ: str, fund brief description
        libraries: list, 'branches', 'research' (NYPL only)
        audns: list, list of 'a', 'j', 'y' values applicable for the fund
        matTypes: list, material types applicable for the fund
    """
    try:
        for k, v in kwargs.items():
            if not v:
                if k == 'libraries':
                    kwargs[k] = []
                elif k == 'audns':
                    kwargs[k] = []
                elif k == 'branches':
                    kwargs[k] = []
                elif k == 'matTypes':
                    kwargs[k] = []
                else:
                    kwargs[k] = None

        mlogger.info('Existing fund new parameters: {}'.format(kwargs))

        with session_scope() as session:
            branches, libraries, audns, matTypes = create_fund_joiner_objs(
                session, **kwargs)
            update_record(session,
                          Fund,
                          kwargs['did'],
                          code=kwargs['code'],
                          describ=kwargs['describ'],
                          audns=audns,
                          branches=branches,
                          matTypes=matTypes,
                          libraries=libraries)

            fund_rec = retrieve_record(session, Fund, did=kwargs['did'])

            mlogger.info(f'Updated record {fund_rec}')
    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error('Unhandled error in Fund update.' f'Traceback: {tb}')
        raise BabelError(exc)
Пример #6
0
def find_matches(cart_id, progbar=None, status_var=None):
    with session_scope() as session:

        if status_var:
            status_var.set('Searching...')

        if progbar:
            count = count_records(session, Order, cart_id=cart_id)
            progbar['value'] = 0
            progbar['maximum'] = count

        cart_rec = retrieve_record(session, Cart, did=cart_id)
        ord_recs = retrieve_records(session, Order, cart_id=cart_id)
        for rec in ord_recs:
            keyword = None
            if rec.resource.isbn:
                keyword = rec.resource.isbn
                babel_dup = babel_resource_match(session,
                                                 cart_rec.system_id,
                                                 cart_rec.library_id,
                                                 isbn=keyword)
            elif rec.resource.upc:
                keyword = rec.resource.upc
                babel_dup = babel_resource_match(upc=keyword)
            else:
                catalog_dup = False
                babel_dup = False

            catalog_dup = catalog_match(cart_rec.system_id, keyword)

            mlogger.debug(
                f'Found following order matches: catalog={catalog_dup}, '
                f'babel={babel_dup}')

            update_record(session,
                          Resource,
                          rec.resource.did,
                          dup_catalog=catalog_dup,
                          dup_babel=babel_dup,
                          dup_timestamp=datetime.now())

            if progbar:
                progbar['value'] += 1
                progbar.update()

    if status_var:
        status_var.set('Search completed.')
Пример #7
0
def copy_grid_data(grid_record):
    mlogger.debug(
        f'Copying grid record did={grid_record.did}, name={grid_record.name}')
    try:
        with session_scope() as session:
            # create new name
            # check if used and adjust
            exists = True
            n = 0
            while exists:
                new_name = f'{grid_record.name}-copy({n})'
                rec = retrieve_record(
                    session, DistGrid,
                    distset_id=grid_record.distset_id,
                    name=new_name)
                if not rec:
                    exists = False
                n += 1

            # compile location data
            locs = []
            for loc in grid_record.gridlocations:
                locs.append(
                    GridLocation(
                        branch_id=loc.branch_id,
                        shelfcode_id=loc.shelfcode_id,
                        qty=loc.qty))

            # # insert to datastore
            rec = insert(
                session, DistGrid,
                distset_id=grid_record.distset_id,
                name=new_name,
                gridlocations=locs)

            mlogger.debug(
                f'Added new record {rec}')

    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error(
            'Unhandled error in copy grid.'
            f'Traceback: {tb}')
        raise BabelError(exc)
Пример #8
0
def create_name_index(model, **kwargs):
    """
    Creates an value/id index of the model
    args:
        model: datatstore class, babel datastore table
        kwargs: dict, filters to be applied to query
    returns:
        idx: dict, {column value: datastore id}
    """
    idx = {}
    with session_scope() as session:
        instances = retrieve_records(session, model, **kwargs)
        for i in instances:
            if i.name is None:
                idx[i.did] = ''
            else:
                idx[i.did] = i.name
    return idx
Пример #9
0
def get_carts_data(system_id, user='******', status=''):
    data = []

    try:
        with session_scope() as session:
            recs = get_cart_data_view_records(session, system_id, user, status)
            for r in recs:
                data.append([
                    r.cart_id, r.cart_name, f'{r.cart_date:%y-%m-%d %H:%M}',
                    r.cart_status, r.cart_owner, r.linked
                ])
        return data

    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error('Unhandled error on cart data retrieval.'
                      f'Traceback: {tb}')
        raise BabelError(exc)
Пример #10
0
def tabulate_funds(cart_id):
    """
    Calculates amount alocated per fund in the cart
    args:
        cart_id: int, datastore cart did
    returns:
        tally: list of tuples(code, amount)
    """
    tally = []
    df = get_cart_details_as_dataframe(cart_id)
    for fund, value in df.groupby('fund'):
        amount = (value['price'] * value['qty']).sum()
        amount = f'{amount:.2f}'
        tally.append(f'{fund}:${amount}')

    with session_scope() as session:
        update_record(session, Cart, did=cart_id, updated=datetime.now())

    return tally
Пример #11
0
def assign_wlo_to_cart(cart_id):
    try:

        with session_scope() as session:
            # determne how many wlo are needed and reserve them
            last_wlo_rec = retrieve_last_record(session, Wlos)
            order_count = count_records(session, Order, cart_id=cart_id)
            wlo_numbers = wlo_pool(last_wlo_rec.did, order_count)

            orders = retrieve_records(session, Order, cart_id=cart_id)
            for o in orders:
                if o.wlo is None:
                    wlo = wlo_numbers.__next__()
                    update_record(session, Order, o.did, wlo=wlo)
                    insert(session, Wlos, did=wlo)

    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error('Unhandled error on assigning wlo to cart.'
                      f'Traceback: {tb}')
        raise BabelError(exc)
Пример #12
0
def export_orders_to_marc_file(fh, saving_status, cart_rec, progbar):
    # this has to be rewritten to make it more transparent
    # and easier to maintain

    try:
        progbar['value'] = 0

        # overwrite existing files
        if os.path.isfile(fh):
            try:
                os.remove(fh)
            except WindowsError as e:
                raise BabelError(f'File in use. Error: {e}')

        with session_scope() as session:
            rec_count = count_records(session, Order, cart_id=cart_rec.did)
            progbar['maximum'] = rec_count

            selector = retrieve_record(session, User, did=cart_rec.user_id)
            blanketPO = cart_rec.blanketPO
            # determine some global values
            if cart_rec.system_id == 1:
                oclc_code = 'BKL'
                selector_code = selector.bpl_code

            elif cart_rec.system_id == 2:
                oclc_code = 'NYP'
                selector_code = selector.nyp_code

            lib_rec = retrieve_record(session,
                                      Library,
                                      did=cart_rec.library_id)
            library_code = lib_rec.code

            ord_recs = retrieve_records(session, Order, cart_id=cart_rec.did)

            for order in ord_recs:
                mat_rec = retrieve_record(session,
                                          MatType,
                                          did=order.matType_id)
                ven_rec = retrieve_record(session, Vendor, did=order.vendor_id)

                if cart_rec.system_id == 1:
                    order.mat_bib = mat_rec.bpl_bib_code
                    order.mat_ord = mat_rec.bpl_ord_code
                    order.vendor = ven_rec.bpl_code
                elif cart_rec.system_id == 2:
                    order.mat_bib = mat_rec.nyp_bib_code
                    order.mat_ord = mat_rec.nyp_ord_code
                    order.vendor = ven_rec.nyp_code

                # retrieve joined values
                rec = retrieve_record(session, Audn, did=order.audn_id)
                order.audn = rec.code
                rec = retrieve_record(session, Lang, did=order.lang_id)
                order.lang = rec.code

                copies = 0
                locs = []
                funds = []
                for loc in order.locations:
                    rec = retrieve_record(session, Branch, did=loc.branch_id)
                    branch = rec.code
                    try:
                        rec = retrieve_record(session,
                                              ShelfCode,
                                              did=loc.shelfcode_id)
                        shelfcode = rec.code
                        shelf_with_audn = rec.includes_audn
                    except AttributeError:
                        shelfcode = ''
                        shelf_with_audn = False
                    try:
                        rec = retrieve_record(session, Fund, did=loc.fund_id)
                        fund = rec.code
                    except AttributeError:
                        fund = ''
                    copies += loc.qty

                    if shelf_with_audn:
                        loc_str = f'{branch}{order.audn}{shelfcode}/{loc.qty}'
                    else:
                        if shelfcode is None:
                            loc_str = f'{branch}/{loc.qty}'
                        else:
                            loc_str = f'{branch}{shelfcode}/{loc.qty}'
                    locs.append(loc_str)

                    fund_str = f'{fund}/{loc.qty}'
                    funds.append(fund_str)

                order.copies = str(copies)
                order.locs = ','.join(locs)
                order.funds = ','.join(funds)
                order.order_date = datetime.strftime(date.today(), '%m-%d-%Y')

                make_bib(fh, oclc_code, library_code, blanketPO, selector_code,
                         order)
                progbar['value'] += 1
                progbar.update()

        saving_status.set('Data saved to MARC file successfully.')

    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error('Unhandled error on saving to MARC.' f'Traceback: {tb}')
        raise BabelError(exc)
Пример #13
0
def get_records(model, **kwargs):
    with session_scope() as session:
        instances = retrieve_records(session, model, **kwargs)
        session.expunge_all()
        return instances
Пример #14
0
def get_codes(model, **kwargs):
    values = []
    with session_scope() as session:
        res = get_column_values(session, model, 'code', **kwargs)
        values = [x.code for x in res]
    return values
Пример #15
0
def validate_cart_data(cart_id):
    issues = OrderedDict()
    iss_count = 0
    with session_scope() as session:
        cart_rec = retrieve_record(session, Cart, did=cart_id)
        if cart_rec.system_id == 1 and cart_rec.library_id != 1:
            iss_count += 1
            issues[0] = "BPL cart library parameter must be set to 'branches'"
        elif cart_rec.system_id == 2:
            if not cart_rec.library_id or cart_rec.library_id == 3:
                iss_count += 1
                issues[0] = 'NYPL carts must specify library'

        n = 0
        order_records = retrieve_records(session, Order, cart_id=cart_id)
        for o in order_records:
            ord_issues = []
            n += 1
            if not o.lang_id:
                iss_count += 1
                ord_issues.append('language')
            if not o.audn_id:
                iss_count += 1
                ord_issues.append('audience')
            if not o.vendor_id:
                iss_count += 1
                ord_issues.append('vendor')
            if not o.matType_id:
                iss_count += 1
                ord_issues.append('material type')
            if not o.resource.title:
                iss_count += 1
                ord_issues.append('title')
            if not o.resource.price_disc:
                iss_count += 1
                ord_issues.append('discount price')

            grid_issues = OrderedDict()
            m = 0
            if o.locations:
                for l in o.locations:
                    m += 1
                    loc_issues = []
                    if not l.branch_id:
                        iss_count += 1
                        loc_issues.append('branch')
                    if not l.shelfcode_id:
                        iss_count += 1
                        loc_issues.append('shelf code')
                    if not l.qty:
                        iss_count += 1
                        loc_issues.append('quantity')
                    if not l.fund_id:
                        iss_count += 1
                        loc_issues.append('fund')
                    else:
                        # verify fund here
                        valid_fund = validate_fund(session, l.fund_id,
                                                   cart_rec.system_id,
                                                   cart_rec.library_id,
                                                   o.audn_id, o.matType_id,
                                                   l.branch_id)
                        if not valid_fund:
                            loc_issues.append('(incorrect) fund')

                    if loc_issues:
                        grid_issues[m] = loc_issues
            else:
                iss_count += 1
                ord_issues.append('locations')

            if ord_issues or grid_issues:
                issues[n] = (ord_issues, grid_issues)

    return iss_count, issues
Пример #16
0
def apply_grid_to_selected_orders(order_ids, grid_id, append=False):
    """
    Datastore transaction that appends or replaces current
    OrderLocation records
    args:
        order_ids: list, list of datastore order dids
        grid_id: int, datastore DistGrid.did
        append: boolean, True appends to existing locations,
                         False replaces existing locations
    """
    with session_scope() as session:
        # retrieve grid location data
        grid_rec = retrieve_record(session, DistGrid, did=grid_id)

        if append:
            # add to existing locations
            for oid in order_ids:
                ord_rec = retrieve_record(session, Order, did=oid)

                for gloc in grid_rec.gridlocations:
                    # find duplicates and merge
                    dup = False
                    for oloc in ord_rec.locations:
                        if oloc.branch_id == gloc.branch_id and \
                                oloc.shelfcode_id == gloc.shelfcode_id:
                            # add quantity to existing oloc
                            dup = True
                            mlogger.debug(
                                'Updating existing '
                                f'OrderLocation.did={oloc.did} '
                                f'with new qty={oloc.qty + gloc.qty}')
                            update_record(session,
                                          OrderLocation,
                                          oloc.did,
                                          order_id=oid,
                                          branch_id=oloc.branch_id,
                                          shelfcode_id=oloc.shelfcode_id,
                                          qty=oloc.qty + gloc.qty,
                                          fund_id=oloc.fund_id)
                    if not dup:
                        mlogger.debug(
                            f'Inserting new OrderLocation for Order.did={oid} '
                            f'based on DistGrid.did={gloc.did}')
                        insert_or_ignore(session,
                                         OrderLocation,
                                         order_id=oid,
                                         branch_id=gloc.branch_id,
                                         shelfcode_id=gloc.shelfcode_id,
                                         qty=gloc.qty)
        else:
            # replace existing locations
            for oid in order_ids:
                # delete exiting locaations
                loc_recs = retrieve_records(session,
                                            OrderLocation,
                                            order_id=oid)
                for oloc in loc_recs:
                    mlogger.debug(f'Deleting OrderLocation.did={oloc.did} '
                                  f'of order.did={oid}')
                    delete_record(session, OrderLocation, did=oloc.did)

                for gloc in grid_rec.gridlocations:
                    mlogger.debug(f'Inserting new OrderLocation based on '
                                  f'DistGrid.did={gloc.did}')
                    insert_or_ignore(session,
                                     OrderLocation,
                                     order_id=oid,
                                     branch_id=gloc.branch_id,
                                     shelfcode_id=gloc.shelfcode_id,
                                     qty=gloc.qty)
Пример #17
0
def create_cart(
        cart_name, system_id, profile_id,
        resource_data, progbar):

    try:
        with session_scope() as session:

            # create Cart record
            name_exists = True
            n = 0
            while name_exists and n < 10:
                name_exists = retrieve_record(
                    session, Cart, name=cart_name)
                if name_exists:
                    n += 1
                    if '(' in cart_name:
                        end = cart_name.index('(')
                        cart_name = cart_name[:end]
                    cart_name = f'{cart_name}({n})'

            if system_id == 1:
                library_id = 1
            else:
                library_id = None

            cart_rec = insert(
                session, Cart,
                name=cart_name,
                created=datetime.now(),
                updated=datetime.now(),
                library_id=library_id,
                system_id=system_id,
                user_id=profile_id)

            progbar['value'] += 1
            progbar.update()

            # create Resource records
            for d in resource_data:
                ord_rec = insert(
                    session, Order,
                    cart_id=cart_rec.did,
                    comment=d.comment)

                insert(
                    session, Resource,
                    order_id=ord_rec.did,
                    title=d.title,
                    add_title=d.add_title,
                    author=d.author,
                    series=d.series,
                    publisher=d.publisher,
                    pub_date=d.pub_date,
                    pub_place=d.pub_place,
                    summary=d.summary,
                    isbn=d.isbn,
                    upc=d.upc,
                    other_no=d.other_no,
                    price_list=d.price_list,
                    price_disc=d.price_disc,
                    desc_url=d.desc_url,
                    misc=d.misc)

                progbar['value'] += 1
                progbar.update()

            session.flush()

            created_cart_id = cart_rec.did
            return created_cart_id

    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error(
            f'Unhandled on sheet ingest. Traceback: {tb}')
        raise BabelError(exc)
Пример #18
0
def get_data_by_identifier(keyword, keyword_type):
    if keyword_type == 'bib #':
        param = Order.bid
    elif keyword_type == 'order #':
        param = Order.oid
    elif keyword_type == 'wlo #':
        param = Order.wlo
    elif keyword_type == 'ISBN':
        param = Resource.isbn
    elif keyword_type == 'UPC':
        param = Resource.upc
    elif keyword_type == 'other #':
        param = Resource.other_no
    elif keyword_type == 'blanketPO':
        param = Cart.blanketPO
    else:
        raise AttributeError('Invalid keyword_type passed')
    mlogger.debug(f'Basic search params: {keyword}, type {param}')

    try:
        with session_scope() as session:
            recs = (session.query(Cart, Order, Resource).join(
                Order, Cart.did == Order.cart_id).join(
                    Resource, Order.did == Resource.order_id).filter(
                        param == keyword).all())

            results = []
            for cart_rec, ord_rec, res_rec in recs:
                # cart
                cart = cart_rec.name
                owner = get_owner(session, cart_rec.user_id)
                system = get_system_name(session, cart_rec.system_id)
                library = get_library_name(session, cart_rec.library_id)
                status = get_status_name(session, cart_rec.status_id)
                created = cart_rec.created
                blanketPO = cart_rec.blanketPO

                # order
                oid = ord_rec.oid
                bid = ord_rec.bid
                wlo = ord_rec.wlo
                po = ord_rec.poPerLine

                lang = get_lang_name(session, ord_rec.lang_id)
                audn_name, audn_code = get_audn_name_and_code(
                    session, ord_rec.audn_id)
                vendor = get_vendor_code(session, ord_rec.vendor_id, system)
                mattype = get_mattype_name(session, ord_rec.matType_id)

                locs = []
                for loc in ord_rec.locations:
                    branch = get_branch_code(session, loc.branch_id)
                    shelfcode = get_shelfcode(session, loc.shelfcode_id,
                                              audn_code)
                    qty = loc.qty
                    fund = get_fund_code(session, loc.fund_id)
                    locs.append(f'{branch}{shelfcode}({qty})/{fund}')

                # resouce
                title = res_rec.title
                author = res_rec.author
                isbn = res_rec.isbn
                upc = res_rec.upc
                other_no = res_rec.other_no

                unit = dict(title=title,
                            author=author,
                            isbn=isbn,
                            upc=upc,
                            other_no=other_no,
                            bid=bid,
                            oid=oid,
                            wlo=wlo,
                            owner=owner,
                            cart=cart,
                            created=created,
                            system=system,
                            library=library,
                            status=status,
                            vendor=vendor,
                            lang=lang,
                            audn_name=audn_name,
                            mattype=mattype,
                            po=po,
                            locs=', '.join(locs))
                results.append(unit)
            session.expunge_all()

        return results

    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error('Unhandled error during Basic search.'
                      f'Traceback: {tb}')
        raise BabelError('Unable to retrieve records.')
Пример #19
0
def insert_fund(**kwargs):
    """
    Adds a new fund with all related data
    args:
        system_id: int, datastore did of NYPL or BPL
        fund_code: str, Sierra fund code
        describ: str, fund brief description
        libraries: list, 'branches', 'research' (NYPL only)
        audns: list, list of 'a', 'j', 'y' values applicable for the fund
        matTypes: list, material types applicable for the fund
    """
    try:
        for k, v in kwargs.items():
            if not v:
                if k == 'libraries':
                    kwargs[k] = ['']
                elif k == 'audns':
                    kwargs[k] = []
                elif k == 'branches':
                    kwargs[k] = []
                elif k == 'matTypes':
                    kwargs[k] = []
                else:
                    kwargs[k] = None

        mlogger.info('New fund record parameters: {}'.format(kwargs))

        with session_scope() as session:
            # check if exists first
            rec = retrieve_record(session,
                                  Fund,
                                  code=kwargs['code'],
                                  system_id=kwargs['system_id'])
            if rec:
                msg = 'Fund record with code: {} already exists.'.format(
                    kwargs['code'])
                mlogger.error(msg)
                raise BabelError('Database Error', msg)
            else:
                branches, libraries, audns, matTypes = create_fund_joiner_objs(
                    session, **kwargs)

                fund_rec = insert(session,
                                  Fund,
                                  code=kwargs['code'],
                                  describ=kwargs['describ'],
                                  system_id=kwargs['system_id'],
                                  audns=audns,
                                  branches=branches,
                                  matTypes=matTypes,
                                  libraries=libraries)

                mlogger.info(f'Added new record {fund_rec}')
            session.expunge_all()

        return fund_rec

    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error('Unhandled error in add Fund.' f'Traceback: {tb}')
        raise BabelError(exc)
Пример #20
0
def save_grid_data(**kwargs):
    """
    used in GridView
    """
    locs = []
    for loc in kwargs['gridlocs']:
        branch_id = get_id_from_index(loc['branch'], kwargs['branch_idx'])
        shelf_id = get_id_from_index(loc['shelf'], kwargs['shelf_idx'])
        if loc['gridloc_id']:
            locs.append(
                GridLocation(
                    did=loc['gridloc_id'],
                    distgrid_id=loc['distgrid_id'],
                    branch_id=branch_id,
                    shelfcode_id=shelf_id,
                    qty=loc['qty']))
        else:
            if loc['distgrid_id']:
                locs.append(
                    GridLocation(
                        distgrid_id=loc['distgrid_id'],
                        branch_id=branch_id,
                        shelfcode_id=shelf_id,
                        qty=loc['qty']
                    ))
            else:
                locs.append(
                    GridLocation(
                        branch_id=branch_id,
                        shelfcode_id=shelf_id,
                        qty=loc['qty']
                    ))

    with session_scope() as session:
        try:
            record = None
            if kwargs['grid_did']:
                update_record(
                    session,
                    DistGrid,
                    kwargs['grid_did'],
                    name=kwargs['name'],
                    distset_id=kwargs['distset_id'],
                    gridlocations=locs)
                record = retrieve_record(
                    session,
                    DistGrid,
                    name=kwargs['name'],
                    distset_id=kwargs['distset_id'])
                mlogger.debug(
                    f'Updated record {record}')
            else:
                record = insert(
                    session,
                    DistGrid,
                    name=kwargs['name'],
                    distset_id=kwargs['distset_id'],
                    gridlocations=locs)
                mlogger.debug(
                    f'Added new record {record}')
            session.expunge_all()
            return record
        except IntegrityError as e:
            raise BabelError(e)
        except InternalError as e:
            raise BabelError(e)
Пример #21
0
def get_cart_details_as_dataframe(cart_id):
    with session_scope() as session:
        stmn = retrieve_cart_details_view_stmn(cart_id)
        df = read_sql(stmn, session.bind)
        return df
Пример #22
0
def save_new_dist_and_grid(system_id,
                           profile_id,
                           grids,
                           branch_idx,
                           shelf_idx,
                           dist=None,
                           grid=None):
    """
    args:
        system_id: int, did from System table
        profile_id: int, did from User table
        grids: dict, grids element of CartView tracker
        dist: str, name of the new DistSet record
        grid: str, name of the new DistGrid record
    """
    try:
        mlogger.debug('Creating new dist/grid from CartView. '
                      f'system: {system_id}, profile: {profile_id}, '
                      f'dist: {dist}, grid: {grid}')

        if profile_id is not None:
            with session_scope() as session:
                dist_rec = insert_or_ignore(session,
                                            DistSet,
                                            system_id=system_id,
                                            user_id=profile_id,
                                            name=dist)
                mlogger.debug(f'Dist_rec: {dist_rec}')

                # check if given grid already exists
                grid_rec = retrieve_record(session,
                                           DistGrid,
                                           name=grid,
                                           distset_id=dist_rec.did)
                mlogger.debug(f'Grid_rec: {grid_rec}')

                # determine new gridLocations
                locations = []
                locs = grids['locs']
                for l in locs:
                    if grid_rec:
                        locations.append(
                            GridLocation(distgrid_id=grid_rec.did,
                                         branch_id=get_id_from_index(
                                             l['branchCbx'].get(), branch_idx),
                                         shelfcode_id=get_id_from_index(
                                             l['shelfCbx'].get(), shelf_idx),
                                         qty=int(l['qtyEnt'].get())))
                    else:
                        locations.append(
                            GridLocation(branch_id=get_id_from_index(
                                l['branchCbx'].get(), branch_idx),
                                         shelfcode_id=get_id_from_index(
                                             l['shelfCbx'].get(), shelf_idx),
                                         qty=int(l['qtyEnt'].get())))
                mlogger.debug(f'New locations: {locations}')

                if grid_rec:
                    mlogger.debug('Updating existing grid_rec.')
                    update_record(session,
                                  DistGrid,
                                  grid_rec.did,
                                  name=grid,
                                  distset_id=dist_rec.did,
                                  gridlocations=locations)
                else:
                    mlogger.debug('Inserting new grid_rec.')
                    insert(session,
                           DistGrid,
                           name=grid,
                           distset_id=dist_rec.did,
                           gridlocations=locations)

    except ValueError as e:
        mlogger.error('User attempted to save new grid with incorrect values.'
                      f'Error: {e}')
        raise BabelError('Your new grid includes invalid values.\n'
                         'Please make sure branch, shelf, and qty are valid.')
Пример #23
0
def create_cart_copy(cart_id, system, user, profile_idx, cart_name, status):
    """
    Creates a copy of a cart
    args:
        cart_id: int, datastore cart did
        system: str, NYPL or BPL
        user: str, profile/user name
        profile_idx: dict, dictionary of user_id (key) and names
        cart_name: str, new cart name
        status: tkinter StringVar
    """
    valid = True
    if not cart_id:
        valid = False
        status.set('Invalid cart id')
    elif not system:
        valid = False
        status.set('Failed. Missing system parameter.')
    elif not user:
        valid = False
        status.set('Failed. Missing profile prameter.')
    elif not cart_name:
        valid = False
        status.set('Failed. Missing new cart name.')

    try:
        with session_scope() as session:
            if cart_id and system and user and cart_name:
                # verify name/user not used:
                if system == 'BPL':
                    system_id = 1
                elif system == 'NYPL':
                    system_id = 2

                rec = retrieve_record(session,
                                      Cart,
                                      system_id=system_id,
                                      user_id=get_id_from_index(
                                          user, profile_idx),
                                      name=cart_name)
                if rec:
                    valid = False
                    status.set('Failed. A cart with the same name'
                               'already exists.\nPlease change the name.')
            if valid:
                # create copy of the original cart
                old_orders = retrieve_records(session, Order, cart_id=cart_id)

                new_orders = []
                for order in old_orders:

                    resource = Resource(title=order.resource.title,
                                        add_title=order.resource.add_title,
                                        author=order.resource.author,
                                        series=order.resource.series,
                                        publisher=order.resource.publisher,
                                        pub_place=order.resource.pub_place,
                                        summary=order.resource.summary,
                                        isbn=order.resource.isbn,
                                        upc=order.resource.upc,
                                        other_no=order.resource.other_no,
                                        price_list=order.resource.price_list,
                                        price_disc=order.resource.price_disc,
                                        desc_url=order.resource.desc_url,
                                        misc=order.resource.misc)

                    new_orders.append(
                        Order(lang_id=order.lang_id,
                              audn_id=order.audn_id,
                              vendor_id=order.vendor_id,
                              matType_id=order.matType_id,
                              poPerLine=order.poPerLine,
                              note=order.note,
                              comment=order.comment,
                              resource=resource))

                insert(session,
                       Cart,
                       name=cart_name,
                       user_id=get_id_from_index(user, profile_idx),
                       system_id=system_id,
                       orders=new_orders)

                status.set('Cart copied successfully.')

    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error('Unhandled error on cart copy.' f'Traceback: {tb}')
        raise BabelError(exc)
Пример #24
0
def apply_globals_to_cart(cart_id, widgets):
    try:

        with session_scope() as session:
            # order data
            okwargs = get_ids_for_order_boxes_values(widgets)
            # locations
            dist_id, grid_name = widgets['globgrid']
            grid_rec = retrieve_record(session,
                                       DistGrid,
                                       distset_id=dist_id,
                                       name=grid_name)
            mlogger.debug(f'Applying globally grid {grid_rec}')

            # resource data
            rkwargs = {}

            discount = None
            if 'discEnt' in widgets:
                if widgets['discEnt'].get() != '':
                    discount = Decimal(widgets['discEnt'].get())

            if 'priceEnt' in widgets:
                if widgets['priceEnt'].get() != '':
                    list_price = Decimal(widgets['priceEnt'].get())
                    rkwargs['price_list'] = list_price
                    if discount:
                        rkwargs['price_disc'] = list_price - (
                            (list_price * discount) / Decimal(100))
                    else:
                        rkwargs['price_disc'] = list_price
            mlogger.debug('Global update to prices: {}, discount: {}'.format(
                rkwargs, discount))

            ord_recs = retrieve_records(session, Order, cart_id=cart_id)

            for rec in ord_recs:
                if grid_rec:
                    olocs = []
                    for l in grid_rec.gridlocations:
                        olocs.append(
                            OrderLocation(order_id=rec.did,
                                          branch_id=l.branch_id,
                                          shelfcode_id=l.shelfcode_id,
                                          qty=l.qty))
                    okwargs['locations'] = olocs
                update_record(session, Order, rec.did, **okwargs)

                if rkwargs:
                    update_record(session, Resource, rec.resource.did,
                                  **rkwargs)

                session.flush()

                if discount is not None:
                    rkwargs['price_disc'] = rec.resource.price_list - (
                        (rec.resource.price_list * discount) / Decimal(100))
                    update_record(session, Resource, rec.resource.did,
                                  **rkwargs)
                    rkwargs = {}

    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error('Unhandled error on applying globals to cart.'
                      f'Traceback: {tb}')
        raise BabelError(exc)