コード例 #1
0
def apply_fund_to_cart(system_id, cart_id, fund_codes):

    try:
        with session_scope() as session:
            cart_rec = retrieve_record(session, Cart, did=cart_id)
            ord_recs = retrieve_records(session, Order, cart_id=cart_id)

            for code in fund_codes:
                fund_rec = retrieve_record(session,
                                           Fund,
                                           code=code,
                                           system_id=system_id)

                fund_audn, fund_mat, fund_branch, fund_lib = valid_fund_ids(
                    fund_rec)

                for orec in ord_recs:
                    audn_match = False
                    mat_match = False
                    library_match = False

                    if orec.audn_id in fund_audn:
                        audn_match = True

                    if orec.matType_id in fund_mat:
                        mat_match = True

                    if cart_rec.library_id in fund_lib:
                        library_match = True

                    for oloc in orec.locations:
                        if oloc.branch_id in fund_branch:
                            mlogger.debug('OrdRec-Fund branch {} match'.format(
                                oloc.branch_id))
                            if audn_match and library_match and mat_match:
                                # update
                                mlogger.debug(
                                    'Complete match. Updating OrderLocation.')
                                update_record(session,
                                              OrderLocation,
                                              oloc.did,
                                              fund_id=fund_rec.did)
                            else:
                                mlogger.debug(
                                    'Incomplete match: lib={}, audn={}, '
                                    'mat={}.'.format(library_match, audn_match,
                                                     mat_match))

    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error('Unhandled error on applying funds to cart.'
                      f'Traceback: {tb}')
        raise BabelError(exc)
コード例 #2
0
def get_ids_for_order_boxes_values(values_dict):
    try:

        kwargs = {}
        with session_scope() as session:
            if values_dict['langCbx'].get() not in ('', 'keep current'):
                rec = retrieve_record(session,
                                      Lang,
                                      name=values_dict['langCbx'].get())
                kwargs['lang_id'] = rec.did

            if values_dict['vendorCbx'].get() not in ('', 'keep current'):
                rec = retrieve_record(session,
                                      Vendor,
                                      name=values_dict['vendorCbx'].get())
                kwargs['vendor_id'] = rec.did

            if values_dict['mattypeCbx'].get() not in ('', 'keep current'):
                rec = retrieve_record(session,
                                      MatType,
                                      name=values_dict['mattypeCbx'].get())
                kwargs['matType_id'] = rec.did

            if values_dict['audnCbx'].get() not in ('', 'keep current'):
                rec = retrieve_record(session,
                                      Audn,
                                      name=values_dict['audnCbx'].get())
                kwargs['audn_id'] = rec.did

            if 'poEnt' in values_dict:
                if values_dict['poEnt'].get().strip() != '':
                    kwargs['poPerLine'] = values_dict['poEnt'].get().strip()

            if 'noteEnt' in values_dict:
                if values_dict['noteEnt'].get().strip() != '':
                    kwargs['note'] = values_dict['noteEnt'].get().strip()

            if 'commentEnt' in values_dict:
                if 'commentEnt' in values_dict:
                    if values_dict['commentEnt'].get().strip() != '':
                        kwargs['comment'] = values_dict['commentEnt'].get(
                        ).strip()

            return kwargs

    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error('Unhandled error on getting ids in cart.'
                      f'Traceback: {tb}')
        raise BabelError(exc)
コード例 #3
0
def get_cart_data_for_order_sheet(cart_id):
    try:
        data_set = []
        with session_scope() as session:
            cart_rec = retrieve_record(session, Cart, did=cart_id)
            order_recs = retrieve_records(session, Order, cart_id=cart_id)
            for rec in order_recs:
                data = []
                data.append(rec.resource.other_no)
                data.append(rec.resource.isbn)
                data.append(rec.resource.title)
                data.append(rec.resource.author)
                total_cost = 0
                total_qty = 0
                for loc in rec.locations:
                    total_cost += loc.qty * rec.resource.price_disc
                    total_qty += loc.qty
                data.append(f'{rec.resource.price_disc:.2f}')
                data.append(total_qty)
                data.append(total_cost)
                data.append(rec.oid)
                data.append(cart_rec.blanketPO)
                data_set.append(data)
            session.expunge_all()

        return data_set

    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error('Unhandled error cart data retrieval.'
                      f'Traceback: {tb}')
        raise BabelError(exc)
コード例 #4
0
def determine_carts_linked(session, cart_ids):
    """
    Determines if all orders in relevant cart have corresponding
    Sierra order and bib number and updates cart linked status
    args:
        cart_ids: list of cart_ids that had their orders updated with oid
    """

    mlogger.debug('Updating carts linked status.')

    # determine time period when wlos were assigned
    for cart_id in cart_ids:
        cart_rec = retrieve_record(session, Cart, did=cart_id)
        # check if all orders have oid
        if cart_rec:
            linked = True
            for o in cart_rec.orders:
                if o.oid is None:
                    mlogger.debug(f'Order did={o.did} missing oid.')
                    linked = False

            if linked:
                mlogger.debug(
                    f'Cart {cart_rec.name} (did={cart_rec.did}) linked.')
                update_record(session, Cart, cart_rec.did, linked=True)
            else:
                mlogger.debug(
                    f'Cart {cart_rec.name} (did={cart_rec.did}) not linked.')
        else:
            mlogger.debug(
                f'Cart with did={cart_id} not linked (missing record).')
コード例 #5
0
def add_sierra_ids_to_orders(source_fh, system_id):
    mlogger.debug(f'Linking IDs initiated system_id-{system_id}.')
    sids = get_sierra_ids(source_fh, system_id)
    try:
        unique_carts = set()
        with session_scope() as session:
            for sid in sids:
                wlo, oid, bid = sid
                ord_rec = retrieve_record(session, Order, wlo=wlo)
                if ord_rec:
                    # record affected cart_id
                    unique_carts.add(ord_rec.cart_id)
                    # update ord rec
                    update_record(session,
                                  Order,
                                  ord_rec.did,
                                  oid=oid,
                                  bid=bid)
                    mlogger.debug(f'Record updated: order_id={ord_rec.did}, '
                                  f'wlo={wlo}, oid={oid}, bid={bid}')

            session.flush()
            # check which carts are linked
            determine_carts_linked(session, unique_carts)

        mlogger.debug('Linking completed.')

    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error('Unhandled error on linking IDs.' f'Traceback: {tb}')
        raise BabelError(exc)
コード例 #6
0
def assign_blanketPO_to_cart(cart_id):
    try:

        with session_scope() as session:
            cart_rec = retrieve_record(session, Cart, did=cart_id)
            if cart_rec.blanketPO is None:
                res = retrieve_unique_vendor_codes_from_cart(
                    session, cart_id, cart_rec.system_id)
                vendor_codes = [code[0] for code in res]
                blanketPO = create_blanketPO(vendor_codes)
                unique = True
                n = 0
                while unique:
                    try:
                        update_record(session,
                                      Cart,
                                      cart_id,
                                      blanketPO=blanketPO)
                        session.flush()
                        unique = False
                    except IntegrityError:
                        session.rollback()
                        n += 1
                        blanketPO = create_blanketPO(vendor_codes, n)

    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error('Unhandled error on assigning blanketPo to cart.'
                      f'Traceback: {tb}')
        raise BabelError(exc)
コード例 #7
0
def determine_needs_validation(cart_id):
    with session_scope() as session:
        cart_rec = retrieve_record(session, Cart, did=cart_id)
        # ignore status 'finlized' and 'archived'
        if cart_rec.status_id in (2, 4):
            return False
        else:
            return True
コード例 #8
0
def get_orders_by_id(order_ids=[]):
    orders = []
    with session_scope() as session:
        for did in order_ids:
            instance = retrieve_record(session, Order, did=did)
            if instance:
                orders.append(instance)
        session.expunge_all()
    return orders
コード例 #9
0
ファイル: data_retriever.py プロジェクト: BookOps-CAT/babel
def get_record(model, **kwargs):
    with session_scope() as session:
        instance = retrieve_record(session, model, **kwargs)
        try:
            session.expunge_all()
            # return instance
        except UnmappedInstanceError:
            pass
        finally:
            return instance
コード例 #10
0
def has_library_assigned(cart_id):
    """
    args:
        cart_id: int, datastore Cart.did
    returns:
        boolean: True is library assigned, False if not
    """
    with session_scope() as session:
        rec = retrieve_record(session, Cart, did=cart_id)
        if rec.library_id:
            return True
        else:
            return False
コード例 #11
0
ファイル: transations_grid.py プロジェクト: BookOps-CAT/babel
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)
コード例 #12
0
def create_fund_joiner_objs(session, **kwargs):
    """
    Preps record objects for FundBranchJoiner, FundLibraryJoiner,
    FundAudnJoiner, and FundMatTypeJoiner
    args:
        branches: list of str
        libraries: list of str
        audns: list of str
        matTypes: list of str
    returns:
        tuple of branches, libraries, audns, matTypes record objects
    """
    branches = []
    for code in kwargs['branches']:
        rec = retrieve_record(session,
                              Branch,
                              code=code,
                              system_id=kwargs['system_id'])
        branches.append(FundBranchJoiner(branch_id=rec.did))

    libraries = []
    for name in kwargs['libraries']:
        rec = retrieve_record(session, Library, name=name)
        libraries.append(FundLibraryJoiner(library_id=rec.did))

    audns = []
    for name in kwargs['audns']:
        rec = retrieve_record(session, Audn, name=name)
        audns.append(FundAudnJoiner(audn_id=rec.did))

    matTypes = []
    for name in kwargs['matTypes']:
        rec = retrieve_record(session, MatType, name=name)
        matTypes.append(FundMatTypeJoiner(matType_id=rec.did))

    return (branches, libraries, audns, matTypes)
コード例 #13
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)
コード例 #14
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.')
コード例 #15
0
ファイル: transations_grid.py プロジェクト: BookOps-CAT/babel
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)
コード例 #16
0
def validate_fund(session, fund_id, system_id, library_id, audn_id, mattype_id,
                  branch_id):
    valid = True
    params = [library_id, audn_id, mattype_id, branch_id]
    for p in params:
        if p is None:
            return True

    fund_rec = retrieve_record(session, Fund, did=fund_id)

    fund_audn, fund_mat, fund_branch, fund_lib = valid_fund_ids(fund_rec)
    if library_id not in fund_lib:
        valid = False
    if audn_id not in fund_audn:
        valid = False
    if mattype_id not in fund_mat:
        valid = False
    if branch_id not in fund_branch:
        valid = False

    return valid
コード例 #17
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)
コード例 #18
0
def get_branch_code(session, branch_id):
    rec = retrieve_record(session, Branch, did=branch_id)
    return rec.code
コード例 #19
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)
コード例 #20
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)
コード例 #21
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)
コード例 #22
0
def get_shelf_rec_id(session, shelf_code):
    rec = retrieve_record(session, ShelfCode, code=shelf_code)
    return rec.did
コード例 #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 get_fund_rec_id(session, fund_code):
    rec = retrieve_record(session, Fund, code=fund_code)
    return rec.did
コード例 #25
0
def get_branch_rec_id(session, branch_code):
    rec = retrieve_record(session, Branch, code=branch_code)
    return rec.did
コード例 #26
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.')
コード例 #27
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
コード例 #28
0
ファイル: transations_grid.py プロジェクト: BookOps-CAT/babel
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)
コード例 #29
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)