Exemple #1
0
def gen_mapfile(vendor, idents, maxage=-1):
    pb = TendrilProgressBar(max=len(idents))
    vendor_obj = controller.get_vendor(name=vendor.cname)
    for ident in idents:
        pb.next(note=ident)
        vpnos, strategy = vendor.search_vpnos(ident)
        if vpnos is not None:
            # pb.writeln("Found: {0}\n".format(ident))
            avpnos = vpnos
        else:
            if strategy not in ['NODEVICE', 'NOVALUE', 'NOT_IMPL']:
                pb.writeln("Not Found: {0:40}::{1}\n".format(ident, strategy))
            avpnos = []
        with get_session() as session:
            # pb.writeln("{0:25} {1}\n".format(ident, avpnos))
            controller.set_strategy(vendor=vendor_obj,
                                    ident=ident,
                                    strategy=strategy,
                                    session=session)
            controller.set_amap_vpnos(vendor=vendor_obj,
                                      ident=ident,
                                      vpnos=avpnos,
                                      session=session)
    pb.finish()
    vendor.map._dump_mapfile()
Exemple #2
0
def export_vendor_map_audit(vendor_obj, max_age=600000):
    if isinstance(vendor_obj, int):
        vendor_obj = vendor_list[vendor_obj]
    mapobj = vendor_obj.map
    outp = os.path.join(config.VENDOR_MAP_AUDIT_FOLDER,
                        vendor_obj.name + '-electronics-audit.csv')
    outf = fsutils.VersionedOutputFile(outp)
    outw = csv.writer(outf)
    total = mapobj.length()
    pb = TendrilProgressBar(max=total)
    for ident in mapobj.get_idents():
        for vpno in mapobj.get_all_partnos(ident):
            try:
                vp = vendor_obj.get_vpart(vpno, ident, max_age)
            except vendors.VendorPartRetrievalError:
                logger.error(
                    "Permanent Retrieval Error while getting part {0} from "
                    "{1}. Removing from Map.".format(vpno, vendor_obj.name)
                )
                mapobj.remove_apartno(vpno, ident)
                continue
            except:
                logger.error("Unhandled Error while getting part {0} from {1}"
                             "".format(vpno, vendor_obj.name))
                raise
            try:
                assert isinstance(vp, vendors.VendorElnPartBase)
                outw.writerow([vp.ident, vp.vpno, vp.mpartno, vp.package,
                               vp.vpartdesc, vp.manufacturer,
                               vp.vqtyavail, vp.abs_moq])
            except AssertionError:
                outw.writerow([vp.ident, vp.vpno, vp.mpartno, None,
                               vp.vpartdesc, vp.manufacturer,
                               vp.vqtyavail, vp.abs_moq])

            pb.next(note=':'.join([ident, vpno]))
            # "\n%f%% %s;%s\nGenerating Vendor Map Audit" % (
            #         percentage, ident, vpno
    pb.finish()
    outf.close()
    logger.info("Written Vendor Map Audit to File : " + vendor_obj.name)
Exemple #3
0
def gen_mapfile(vendor, idents):
    pb = TendrilProgressBar(max=len(idents))
    vendor_obj = controller.get_vendor(name=vendor._name)
    for ident in idents:
        pb.next(note=ident)
        vpnos, strategy = vendor.search_vpnos(ident)
        if vpnos is not None:
            # pb.writeln("Found: {0}\n".format(ident))
            avpnos = vpnos
        else:
            if strategy not in ['NODEVICE', 'NOVALUE',
                                'NOT_IMPL']:
                pb.writeln("Not Found: {0:40}::{1}\n".format(ident, strategy))
            avpnos = []
        with get_session() as session:
            # pb.writeln("{0:25} {1}\n".format(ident, avpnos))
            controller.set_strategy(vendor=vendor_obj, ident=ident,
                                    strategy=strategy, session=session)
            controller.set_amap_vpnos(vendor=vendor_obj, ident=ident,
                                      vpnos=avpnos, session=session)
    pb.finish()
    vendor.map._dump_mapfile()
Exemple #4
0
def export_vendor_map_audit(vendor_obj, max_age=-1):
    if isinstance(vendor_obj, int):
        vendor_obj = vendor_list[vendor_obj]
    mapobj = vendor_obj.map
    outp = os.path.join(VENDOR_MAP_AUDIT_FOLDER,
                        vendor_obj.name + '-electronics-audit.csv')
    outf = fsutils.VersionedOutputFile(outp)
    outw = csv.writer(outf)
    total = mapobj.length()
    pb = TendrilProgressBar(max=total)
    for ident in mapobj.get_idents():
        for vpno in mapobj.get_all_partnos(ident):
            try:
                vp = vendor_obj.get_vpart(vpno, ident, max_age)
            except VendorPartRetrievalError:
                logger.error(
                    "Permanent Retrieval Error while getting part {0} from "
                    "{1}. Removing from Map.".format(vpno, vendor_obj.name))
                mapobj.remove_apartno(vpno, ident)
                continue
            except:
                logger.error("Unhandled Error while getting part {0} from {1}"
                             "".format(vpno, vendor_obj.name))
                raise
            if isinstance(vp, VendorElnPartBase):
                row = [
                    vp.ident, vp.vpno, vp.mpartno, vp.package, vp.vpartdesc,
                    vp.manufacturer, vp.vqtyavail, vp.abs_moq
                ]
            else:
                row = [
                    vp.ident, vp.vpno, vp.mpartno, None, vp.vpartdesc,
                    vp.manufacturer, vp.vqtyavail, vp.abs_moq
                ]

            outw.writerow([six.text_type(s).encode("utf-8") for s in row])

            pb.next(note=':'.join([ident, vpno]))
            # "\n%f%% %s;%s\nGenerating Vendor Map Audit" % (
            #         percentage, ident, vpno
    pb.finish()
    outf.close()
    logger.info("Written Vendor Map Audit to File : " + vendor_obj.name)
Exemple #5
0
def gen_verification_checklist(invoice, target_folder, serialno):
    """
    Generates the Customs Duties / Checklist Verification document.

    :param invoice: The invoice object with customs information
    :type invoice: :class:`tendril.sourcing.customs.CustomsInvoice`
    :param target_folder: The folder in which the generated files
                          should be written to
    :param serialno: The serial number of the Customs documentation set
    :type serialno: str
    :return: The output file tuple (path, type)

    .. rubric:: Template Used

    ``tendril/dox/templates/customs/verification-duties.tex``
    (:download:`Included version
    <../../tendril/dox/templates/customs/verification-duties.tex>`)

    .. rubric:: Stage Keys Provided
    .. list-table::

        * - ``date``
          - The date the documents were generated at,
            from :func:`datetime.date.today`.
        * - ``signatory``
          - The name of the person who 'signs' the document, from
            :data:`tendril.config.legacy.COMPANY_GOVT_POINT`.
        * - ``inv_no``
          - The vendor's invoice number.
        * - ``inv_date``
          - The date of the vendor's invoice.
        * - ``given_data``
          - A dict containing various facts about the invoice. See
            :attr:`tendril.sourcing.customs.CustomsInvoice.given_data`.
        * - ``lines``
          - A list of :class:`tendril.sourcing.customs.CustomsInvoiceLine`
            instances.
        * - ``invoice``
          - The :class:`tendril.sourcing.customs.CustomsInvoice` instance.
        * - ``sno``
          - The serial number of the document.
        * - ``summary``
          - A list of dicts containing the summary of the customs duties
            applicable against a particular section, as described below

    .. list-table:: Summary keys

        * - ``section``
          - The HS section, a
            :class:`tendril.sourcing.customs.CustomsSection`` instance.
        * - ``code``
          - The HS section code.
        * - ``name``
          - The HS section name.
        * - ``idxs``
          - Line numbers classified into this line.
        * - ``qty``
          - Total quantity of all lines classified into this line.
        * - ``assessablevalue``
          - Total assessable value of all lines classified into this line.
        * - ``bcd``
          - Total Basic Customs Duty applicable against this section.
        * - ``cvd``
          - Total Countervailing Duty applicable against this section.
        * - ``acvd``
          - Total Additional Countervailing Duty applicable against
            this section.
        * - ``cec``
          - Total Education Cess on Customs Duty applicable against
            this section.
        * - ``cshec``
          - Total Secondary and Higher Education Cess on Customs Duty
            applicable against this section.
        * - ``cvdec``
          - Total Education Cess on Countervailing Duty applicable
            against this section.
        * - ``cvdshec``
          - Total Secondary and Higher Education Cess on Countervailing Duty
            applicable against this section.

    """
    print("Generating Customs Duty Verification Checklist")
    outpath = os.path.join(
        target_folder,
        "customs-verification-duties-" + str(invoice.inv_no) + ".pdf")
    summary = []
    pb = TendrilProgressBar(max=len(invoice.hssections))
    print("Collating Section Summaries...")
    for section in invoice.hssections:
        secsum = {
            'section':
            section,
            'code':
            section.code,
            'name':
            section.name,
            'idxs':
            invoice.getsection_idxs(hssection=section),
            'assessablevalue':
            invoice.getsection_assessabletotal(hssection=section),
            'qty':
            invoice.getsection_qty(hssection=section),
            'bcd':
            sum([
                x.bcd.value
                for x in invoice.getsection_lines(hssection=section)
            ]),
            'cvd':
            sum([
                x.cvd.value
                for x in invoice.getsection_lines(hssection=section)
            ]),
            'acvd':
            sum([
                x.acvd.value
                for x in invoice.getsection_lines(hssection=section)
            ]),
            'cec':
            sum([
                x.cec.value
                for x in invoice.getsection_lines(hssection=section)
            ]),
            'cshec':
            sum([
                x.cshec.value
                for x in invoice.getsection_lines(hssection=section)
            ]),
            'cvdec':
            sum([
                x.cvdec.value
                for x in invoice.getsection_lines(hssection=section)
            ]),
            'cvdshec':
            sum([
                x.cvdshec.value
                for x in invoice.getsection_lines(hssection=section)
            ]),
        }
        summary.append(secsum)
        pb.next(note=section.code + ' ' + section.name)
    pb.finish()
    pb = TendrilProgressBar(max=len(invoice.lines))
    pb_summary = TendrilProgressBar(max=len(summary))
    stage = {
        'date': datetime.date.today().isoformat(),
        'signatory': COMPANY_GOVT_POINT,
        'inv_no': invoice.inv_no,
        'inv_date': invoice.inv_date,
        'given_data': invoice.given_data,
        'lines': invoice.lines,
        'summary': summary,
        'invoice': invoice,
        'sno': serialno + '.7',
        'pb': pb,
        'pb_summary': pb_summary
    }
    print("Rendering...")
    outpath = render.render_pdf(stage, 'customs/verification-duties.tex',
                                outpath)
    return outpath, 'CUST-VERIF-BOE'
Exemple #6
0
def gen_verification_checklist(invoice, target_folder, serialno):
    """
    Generates the Customs Duties / Checklist Verification document.

    :param invoice: The invoice object with customs information
    :type invoice: :class:`tendril.sourcing.customs.CustomsInvoice`
    :param target_folder: The folder in which the generated files
                          should be written to
    :param serialno: The serial number of the Customs documentation set
    :type serialno: str
    :return: The output file tuple (path, type)

    .. rubric:: Template Used

    ``tendril/dox/templates/customs/verification-duties.tex``
    (:download:`Included version
    <../../tendril/dox/templates/customs/verification-duties.tex>`)

    .. rubric:: Stage Keys Provided
    .. list-table::

        * - ``date``
          - The date the documents were generated at,
            from :func:`datetime.date.today`.
        * - ``signatory``
          - The name of the person who 'signs' the document, from
            :data:`tendril.utils.config.COMPANY_GOVT_POINT`.
        * - ``inv_no``
          - The vendor's invoice number.
        * - ``inv_date``
          - The date of the vendor's invoice.
        * - ``given_data``
          - A dict containing various facts about the invoice. See
            :attr:`tendril.sourcing.customs.CustomsInvoice.given_data`.
        * - ``lines``
          - A list of :class:`tendril.sourcing.customs.CustomsInvoiceLine`
            instances.
        * - ``invoice``
          - The :class:`tendril.sourcing.customs.CustomsInvoice` instance.
        * - ``sno``
          - The serial number of the document.
        * - ``summary``
          - A list of dicts containing the summary of the customs duties
            applicable against a particular section, as described below

    .. list-table:: Summary keys

        * - ``section``
          - The HS section, a
            :class:`tendril.sourcing.customs.CustomsSection`` instance.
        * - ``code``
          - The HS section code.
        * - ``name``
          - The HS section name.
        * - ``idxs``
          - Line numbers classified into this line.
        * - ``qty``
          - Total quantity of all lines classified into this line.
        * - ``assessablevalue``
          - Total assessable value of all lines classified into this line.
        * - ``bcd``
          - Total Basic Customs Duty applicable against this section.
        * - ``cvd``
          - Total Countervailing Duty applicable against this section.
        * - ``acvd``
          - Total Additional Countervailing Duty applicable against
            this section.
        * - ``cec``
          - Total Education Cess on Customs Duty applicable against
            this section.
        * - ``cshec``
          - Total Secondary and Higher Education Cess on Customs Duty
            applicable against this section.
        * - ``cvdec``
          - Total Education Cess on Countervailing Duty applicable
            against this section.
        * - ``cvdshec``
          - Total Secondary and Higher Education Cess on Countervailing Duty
            applicable against this section.

    """
    print("Generating Customs Duty Verification Checklist")
    outpath = os.path.join(
        target_folder,
        "customs-verification-duties-" + str(invoice.inv_no) + ".pdf"
    )
    summary = []
    pb = TendrilProgressBar(max=len(invoice.hssections))
    print("Collating Section Summaries...")
    for section in invoice.hssections:
        secsum = {'section': section,
                  'code': section.code,
                  'name': section.name,
                  'idxs': invoice.getsection_idxs(hssection=section),
                  'assessablevalue':
                  invoice.getsection_assessabletotal(hssection=section),
                  'qty': invoice.getsection_qty(hssection=section),
                  'bcd':
                  sum([x.bcd.value for x in
                       invoice.getsection_lines(hssection=section)]),
                  'cvd':
                  sum([x.cvd.value for x in
                       invoice.getsection_lines(hssection=section)]),
                  'acvd':
                  sum([x.acvd.value for x in
                       invoice.getsection_lines(hssection=section)]),
                  'cec':
                  sum([x.cec.value for x in
                       invoice.getsection_lines(hssection=section)]),
                  'cshec':
                  sum([x.cshec.value for x in
                       invoice.getsection_lines(hssection=section)]),
                  'cvdec':
                  sum([x.cvdec.value for x in
                       invoice.getsection_lines(hssection=section)]),
                  'cvdshec':
                  sum([x.cvdshec.value for x in
                       invoice.getsection_lines(hssection=section)]),
                  }
        summary.append(secsum)
        pb.next(note=section.code + ' ' + section.name)
    pb.finish()
    pb = TendrilProgressBar(max=len(invoice.lines))
    pb_summary = TendrilProgressBar(max=len(summary))
    stage = {'date': datetime.date.today().isoformat(),
             'signatory': COMPANY_GOVT_POINT,
             'inv_no': invoice.inv_no,
             'inv_date': invoice.inv_date,
             'given_data': invoice.given_data,
             'lines': invoice.lines,
             'summary': summary,
             'invoice': invoice,
             'sno': serialno + '.7',
             'pb': pb,
             'pb_summary': pb_summary}
    print("Rendering...")
    outpath = render.render_pdf(
        stage, 'customs/verification-duties.tex', outpath
    )
    return outpath, 'CUST-VERIF-BOE'
Exemple #7
0
            os.linesep + os.path.join(orderfolder, 'cobom.csv')
        )
        cobom.dump(f)

    orders_path = os.path.join(orderfolder, 'purchase-orders')
    if not os.path.exists(orders_path):
        os.makedirs(orders_path)

    reservations_path = os.path.join(orderfolder, 'reservations')
    if not os.path.exists(reservations_path):
        os.makedirs(reservations_path)

    unsourced = []
    deferred = []
    nlines = len(cobom.lines)
    pb = TendrilProgressBar(max=nlines)

    # TODO Heavily refactor

    for pbidx, line in enumerate(cobom.lines):
        if logger.getEffectiveLevel() >= log.INFO or \
                (PRIORITIZE is False and USE_STOCK is False):
            percentage = (float(pbidx) / nlines) * 100.00
            pb.next(note=line.ident)
            # "\n{0:>7.4f}% {1:<40} Qty:{2:<4}\n"
            # "Constructing Shortage File, Reservations, and Preparing Orders".format(  # noqa
            #     percentage, line.ident, line.quantity
            shortage = 0
        if USE_STOCK is True:
            if PRIORITIZE is False:
                for idx, descriptor in enumerate(cobom.descriptors):
Exemple #8
0
def get_csil_prices(params=exparams, rval=None):
    if rval is None:
        rval = {}
    delivery_codes = {
        # 3: '3#333',
        # 5: '5#334',
        7: '7#529',
        10: '10#1452',
        12: '12#7271',
        15: '15#1453',
        18: '18#7272',
        21: '21#7273'
    }

    delivery_times = sorted(delivery_codes.keys())

    layers_codes = {
        1: '2180',
        2: '2181',
        4: '2183',
        6: '2184',
    }

    browser = splinter.Browser('firefox', profile=FIREFOX_PROFILE_PATH)
    url = 'http://login.pcbpower.com/V2/login.aspx'
    browser.visit(url)
    values = {'txtUserName': dvobj.username, 'txtPassword': dvobj.password}
    browser.fill_form(values)
    button = browser.find_by_name('btnlogin')
    button.click()
    link = browser.find_by_id('ctl00_aPlaceOrder')
    link.click()

    values = OrderedDict()
    values['ctl00$ContentPlaceHolder1$txtPCBName'] = params['pcbname']
    values['ctl00$ContentPlaceHolder1$ddlLayers'] = layers_codes[
        params['layers']]  # noqa
    values['ctl00$ContentPlaceHolder1$txtDimX'] = str(params['dX'])
    values['ctl00$ContentPlaceHolder1$txtDimY'] = str(params['dY'])
    if 'qty' in params.keys():
        values['ctl00$ContentPlaceHolder1$txtQuantity'] = str(
            params['qty'][1])  # noqa
    else:
        values['ctl00$ContentPlaceHolder1$txtQuantity'] = '1'
    values['ctl00$ContentPlaceHolder1$DDLsurfacefinish'] = params['finish']
    if 'time' in params.keys():
        values['ctl00$ContentPlaceHolder1$ddlDelTerms'] = delivery_codes[
            params['time']]  # noqa
    else:
        values['ctl00$ContentPlaceHolder1$ddlDelTerms'] = delivery_codes[7]

    if not browser.is_element_present_by_id('shortNotiText', wait_time=100):
        raise Exception
    ready = False
    timeout = 10
    while not ready and timeout:
        el = browser.find_by_id('shortNotiText')
        if el[0].text == u"We're online":
            ready = True
        timeout -= 1
        time.sleep(1)
    time.sleep(5)
    browser.fill_form(values)

    try:
        oldt = browser.find_by_id('ctl00_ContentPlaceHolder1_lblUnitPrc').text
    except AttributeError:
        oldt = ''
    # qty = str(params['qty'][1])
    # oldv = qty
    time.sleep(2)
    button = browser.find_by_id('ctl00_ContentPlaceHolder1_btnCalculate')

    button.click()
    time.sleep(2)
    button = browser.find_by_id('ctl00_ContentPlaceHolder1_btnCalculate')

    button.click()

    try:
        newt = browser.find_by_id('ctl00_ContentPlaceHolder1_lblUnitPrc').text
    except AttributeError:
        newt = ''
    try:
        newtt = browser.find_by_id(
            'ctl00_ContentPlaceHolder1_lblTotalPrice').text  # noqa
    except AttributeError:
        newtt = ''
    while oldt == newt:
        try:
            newt = browser.find_by_id(
                'ctl00_ContentPlaceHolder1_lblUnitPrc').text  # noqa
        except AttributeError:
            newt = ''
        try:
            newtt = browser.find_by_id(
                'ctl00_ContentPlaceHolder1_lblTotalPrice').text  # noqa
        except AttributeError:
            newtt = ''
        time.sleep(0.5)
    oldt = newt
    oldtt = newtt
    pb = TendrilProgressBar(max=len(params['qty']))
    for qty in params['qty'][2:]:
        lined = {}
        while browser.find_by_name('ctl00$ContentPlaceHolder1$txtQuantity'
                                   )[0].value != '':  # noqa
            browser.type('ctl00$ContentPlaceHolder1$txtQuantity', '\b')
            time.sleep(0.1)
        browser.type('ctl00$ContentPlaceHolder1$txtQuantity', str(qty))
        time.sleep(0.1)
        browser.type('ctl00$ContentPlaceHolder1$txtQuantity', '\t')
        if qty > 4:
            loi = [10]
        else:
            loi = [10]
        pb.next(note="{0} {1}".format(qty, loi))
        # "\n{0:>7.4f}% {1:<40} Qty: {2:<10} DTS: {3:<4}\nGenerating PCB Pricing".format(  # noqa
        #               percentage, params['pcbname'], qty, loi)
        for dt_s in loi:
            dt_idx = delivery_times.index(dt_s)
            dts = delivery_times[dt_idx:dt_idx + 3]
            browser.select('ctl00$ContentPlaceHolder1$ddlDelTerms',
                           delivery_codes[dt_s])  # noqa
            time.sleep(1)
            while True:
                try:
                    try:
                        newt = browser.find_by_id(
                            'ctl00_ContentPlaceHolder1_lblUnitPrc'
                        ).text  # noqa
                    except AttributeError:
                        newt = ''
                    try:
                        # newt1 = ''
                        # newt2 = ''
                        newt1 = browser.find_by_id(
                            'ctl00_ContentPlaceHolder1_lblnextunitprc1'
                        ).text  # noqa
                        newt2 = browser.find_by_id(
                            'ctl00_ContentPlaceHolder1_lblnextunitprc2'
                        ).text  # noqa
                    except AttributeError:
                        newt1 = ''
                        newt2 = ''
                    break
                except selenium.common.exceptions.StaleElementReferenceException:  # noqa
                    logger.warning("Selenium Exception Caught. Retrying")
                    continue

            timeout = 25
            while oldt == newt and oldtt == newtt and newt is not '' and timeout > 0:  # noqa
                timeout -= 1
                time.sleep(1)
                while True:
                    try:
                        try:
                            newt = browser.find_by_id(
                                'ctl00_ContentPlaceHolder1_lblUnitPrc'
                            ).text  # noqa
                        except AttributeError:
                            newt = ''
                        try:
                            # newt1 = ''
                            # newt2 = ''
                            newt1 = browser.find_by_id(
                                'ctl00_ContentPlaceHolder1_lblnextunitprc1'
                            ).text  # noqa
                            newt2 = browser.find_by_id(
                                'ctl00_ContentPlaceHolder1_lblnextunitprc2'
                            ).text  # noqa
                        except AttributeError:
                            newt1 = ''
                            newt2 = ''
                        break
                    except selenium.common.exceptions.StaleElementReferenceException:  # noqa
                        logger.warning("Selenium Exception Caught. Retrying")
                        continue
                try:
                    newtt = browser.find_by_id(
                        'ctl00_ContentPlaceHolder1_lblTotalPrice').text  # noqa
                except AttributeError:
                    newtt = ''
            try:
                lined[dts[0]] = locale.atof(newt)
                if newt1 != '':
                    lined[dts[1]] = locale.atof(newt1)
                if newt2 != '':
                    lined[dts[2]] = locale.atof(newt2)
            except ValueError:
                logger.warning("Caught Exception at CSIL Website. Retrying.")
                browser.quit()
                return get_csil_prices(params, rval)
            oldt = newt
            oldtt = newtt
        params['qty'].remove(qty)
        # print lined
        rval[qty] = lined
    browser.quit()
    return rval
Exemple #9
0
def get_csil_prices(params=exparams, rval=None):
    if rval is None:
        rval = {}
    delivery_codes = {
        # 3: '3#333',
        # 5: '5#334',
        7: '7#529',
        10: '10#1452',
        12: '12#7271',
        15: '15#1453',
        18: '18#7272',
        21: '21#7273'
    }

    delivery_times = sorted(delivery_codes.keys())

    layers_codes = {
        1: '2180',
        2: '2181',
        4: '2183',
        6: '2184',
    }

    browser = splinter.Browser('firefox', profile=FIREFOX_PROFILE_PATH)
    url = 'http://www.pcbpower.com:8080'
    browser.visit(url)
    values = {
        'ctl00$ContentPlaceHolder1$txtUserName': dvobj.username,
        'ctl00$ContentPlaceHolder1$txtPassword': dvobj.password
    }
    browser.fill_form(values)
    button = browser.find_by_name('ctl00$ContentPlaceHolder1$btnlogin')
    button.click()
    link = browser.find_by_id('ctl00_aPlaceOrder')
    link.click()

    values = OrderedDict()
    values['ctl00$ContentPlaceHolder1$txtPCBName'] = params['pcbname']
    values['ctl00$ContentPlaceHolder1$ddlLayers'] = layers_codes[params['layers']]  # noqa
    values['ctl00$ContentPlaceHolder1$txtDimX'] = str(params['dX'])
    values['ctl00$ContentPlaceHolder1$txtDimY'] = str(params['dY'])
    if 'qty' in params.keys():
        values['ctl00$ContentPlaceHolder1$txtQuantity'] = str(params['qty'][1])  # noqa
    else:
        values['ctl00$ContentPlaceHolder1$txtQuantity'] = '1'
    values['ctl00$ContentPlaceHolder1$DDLsurfacefinish'] = params['finish']
    if 'time' in params.keys():
        values['ctl00$ContentPlaceHolder1$ddlDelTerms'] = delivery_codes[params['time']]  # noqa
    else:
        values['ctl00$ContentPlaceHolder1$ddlDelTerms'] = delivery_codes[7]

    if not browser.is_element_present_by_id('shortNotiText', wait_time=100):
        raise Exception
    ready = False
    timeout = 10
    while not ready and timeout:
        el = browser.find_by_id('shortNotiText')
        if el[0].text == u"We're online":
            ready = True
        timeout -= 1
        time.sleep(1)
    time.sleep(5)
    browser.fill_form(values)

    try:
        oldt = browser.find_by_id('ctl00_ContentPlaceHolder1_lblUnitPrc').text
    except AttributeError:
        oldt = ''
    # qty = str(params['qty'][1])
    # oldv = qty
    time.sleep(2)
    button = browser.find_by_id('ctl00_ContentPlaceHolder1_btnCalculate')

    button.click()
    time.sleep(2)
    button = browser.find_by_id('ctl00_ContentPlaceHolder1_btnCalculate')

    button.click()

    try:
        newt = browser.find_by_id('ctl00_ContentPlaceHolder1_lblUnitPrc').text
    except AttributeError:
        newt = ''
    try:
        newtt = browser.find_by_id('ctl00_ContentPlaceHolder1_lblTotalPrice').text  # noqa
    except AttributeError:
        newtt = ''
    while oldt == newt:
        try:
            newt = browser.find_by_id('ctl00_ContentPlaceHolder1_lblUnitPrc').text  # noqa
        except AttributeError:
            newt = ''
        try:
            newtt = browser.find_by_id('ctl00_ContentPlaceHolder1_lblTotalPrice').text  # noqa
        except AttributeError:
            newtt = ''
        time.sleep(0.5)
    oldt = newt
    oldtt = newtt
    pb = TendrilProgressBar(max=len(params['qty']))
    for qty in params['qty'][2:]:
        lined = {}
        while browser.find_by_name('ctl00$ContentPlaceHolder1$txtQuantity')[0].value != '':  # noqa
            browser.type('ctl00$ContentPlaceHolder1$txtQuantity', '\b')
            time.sleep(0.1)
        browser.type('ctl00$ContentPlaceHolder1$txtQuantity', str(qty))
        time.sleep(0.1)
        browser.type('ctl00$ContentPlaceHolder1$txtQuantity', '\t')
        if qty > 4:
            loi = [10]
        else:
            loi = [10]
        pb.next(note="{0} {1}".format(qty, loi))
        # "\n{0:>7.4f}% {1:<40} Qty: {2:<10} DTS: {3:<4}\nGenerating PCB Pricing".format(  # noqa
        #               percentage, params['pcbname'], qty, loi)
        for dt_s in loi:
            dt_idx = delivery_times.index(dt_s)
            dts = delivery_times[dt_idx:dt_idx + 3]
            browser.select('ctl00$ContentPlaceHolder1$ddlDelTerms', delivery_codes[dt_s])  # noqa
            time.sleep(1)
            while True:
                try:
                    try:
                        newt = browser.find_by_id('ctl00_ContentPlaceHolder1_lblUnitPrc').text  # noqa
                    except AttributeError:
                        newt = ''
                    try:
                        # newt1 = ''
                        # newt2 = ''
                        newt1 = browser.find_by_id('ctl00_ContentPlaceHolder1_lblnextunitprc1').text  # noqa
                        newt2 = browser.find_by_id('ctl00_ContentPlaceHolder1_lblnextunitprc2').text  # noqa
                    except AttributeError:
                        newt1 = ''
                        newt2 = ''
                    break
                except selenium.common.exceptions.StaleElementReferenceException:  # noqa
                    logger.warning("Selenium Exception Caught. Retrying")
                    continue

            timeout = 25
            while oldt == newt and oldtt == newtt and newt is not '' and timeout > 0:  # noqa
                timeout -= 1
                time.sleep(1)
                while True:
                    try:
                        try:
                            newt = browser.find_by_id('ctl00_ContentPlaceHolder1_lblUnitPrc').text  # noqa
                        except AttributeError:
                            newt = ''
                        try:
                            # newt1 = ''
                            # newt2 = ''
                            newt1 = browser.find_by_id('ctl00_ContentPlaceHolder1_lblnextunitprc1').text  # noqa
                            newt2 = browser.find_by_id('ctl00_ContentPlaceHolder1_lblnextunitprc2').text  # noqa
                        except AttributeError:
                            newt1 = ''
                            newt2 = ''
                        break
                    except selenium.common.exceptions.StaleElementReferenceException:  # noqa
                        logger.warning("Selenium Exception Caught. Retrying")
                        continue
                try:
                    newtt = browser.find_by_id('ctl00_ContentPlaceHolder1_lblTotalPrice').text  # noqa
                except AttributeError:
                    newtt = ''
            try:
                lined[dts[0]] = locale.atof(newt)
                if newt1 != '':
                    lined[dts[1]] = locale.atof(newt1)
                if newt2 != '':
                    lined[dts[2]] = locale.atof(newt2)
            except ValueError:
                logger.warning("Caught Exception at CSIL Website. Retrying.")
                browser.quit()
                return get_csil_prices(params, rval)
            oldt = newt
            oldtt = newtt
        params['qty'].remove(qty)
        # print lined
        rval[qty] = lined
    browser.quit()
    return rval
Exemple #10
0
        logger.info('Exporting Composite Output BOM to File : ' + os.linesep +
                    os.path.join(orderfolder, 'cobom.csv'))
        cobom.dump(f)

    orders_path = os.path.join(orderfolder, 'purchase-orders')
    if not os.path.exists(orders_path):
        os.makedirs(orders_path)

    reservations_path = os.path.join(orderfolder, 'reservations')
    if not os.path.exists(reservations_path):
        os.makedirs(reservations_path)

    unsourced = []
    deferred = []
    nlines = len(cobom.lines)
    pb = TendrilProgressBar(max=nlines)

    # TODO Heavily refactor

    for pbidx, line in enumerate(cobom.lines):
        if logger.getEffectiveLevel() >= log.INFO or \
                (PRIORITIZE is False and USE_STOCK is False):
            percentage = (float(pbidx) / nlines) * 100.00
            pb.next(note=line.ident)
            # "\n{0:>7.4f}% {1:<40} Qty:{2:<4}\n"
            # "Constructing Shortage File, Reservations, and Preparing Orders".format(  # noqa
            #     percentage, line.ident, line.quantity
            shortage = 0
        if USE_STOCK is True:
            if PRIORITIZE is False:
                for idx, descriptor in enumerate(cobom.descriptors):