Beispiel #1
0
def add_resource(cart_id, **kwargs):
    try:
        with session_scope() as session:
            orec = insert(session, Order, cart_id=cart_id)
            kwargs['order_id'] = orec.did
            insert(session, Resource, **kwargs)
    except Exception as exc:
        _, _, exc_traceback = sys.exc_info()
        tb = format_traceback(exc, exc_traceback)
        mlogger.error('Unhandled error on updating resource.'
                      f'Traceback: {tb}')
        raise BabelError(exc)
Beispiel #2
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)
Beispiel #3
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)
Beispiel #4
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)
Beispiel #5
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)
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)
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)
Beispiel #8
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.')
Beispiel #9
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)