class SpecialOrder(SQLObjectWithFormGlue):
    _passwd = configuration.get("db_col_password")
    _aes = AES.new(_passwd + (16 - (len(_passwd[0:16]))) * b"{", AES.MODE_CBC,
                   b"0" * 16)

    class sqlmeta:
        fromDatabase = True

    dateOrdered = DateCol(default=Now.now)
    titles = RelatedJoin("Title",
                         intermediateTable="title_special_order",
                         createRelatedTable=False)
    title_pivots = MultipleJoin("TitleSpecialOrder")

    def _get_contactInfo(self):
        return self._SO_get_contactInfo()

    def _set_contactInfo(self, value):
        self._SO_set_contactInfo(value)

    def _get_customerName(self):
        return self._SO_get_customerName()

    def _set_customerName(self, value):
        self._SO_set_customerName(value)
def print_barcode_label_old(isbn='', booktitle='', author='', ourprice=0, listprice=0, num_copies=1):
    import sys
    print(type(isbn), type(isbn1), type(booktitle), file=sys.stderr)
    print(isbn, booktitle, author, ourprice, listprice, num_copies, file=sys.stderr)
    rl_config.warnOnMissingFontGlyphs = 1
    try:
        registerFont(TTFont('Courier New', 'Courier New.ttf'))
        registerFont(TTFont('Courier New Bold', 'Courier New Bold.ttf'))
        registerFont(TTFont('Courier New Italic', 'Courier New Italic.ttf'))
        registerFont(TTFont('Courier New Bold Italic', 'Courier New Bold Italic.ttf'))
        registerFontFamily('Courier New', normal='Courier New', bold='Courier New Bold', italic='Courier New Italic', boldItalic='Courier New Bold Italic')
    except TTFError:
        registerFont(TTFont('Courier New', 'Courier_New.ttf'))
        registerFont(TTFont('Courier New Bold', 'Courier_New_Bold.ttf'))
        registerFont(TTFont('Courier New Italic', 'Courier_New_Italic.ttf'))
        registerFont(TTFont('Courier New Bold Italic', 'Courier_New_Bold_Italic.ttf'))
        registerFontFamily('Courier New', normal='Courier New', bold='Courier New Bold', italic='Courier New Italic', boldItalic='Courier New Bold Italic')

    font = 'Courier New Bold'
    font_size = 9
    format_ourprice='$' + ('%3.2f' % float(str(ourprice).strip('$')))
    doc_width = 2.4*inch
    doc_height = 2*inch
    margin = 0.1*inch
    column_width = doc_width - 2*margin
    column_height = doc_height - 2*margin
    ourprice_width = stringWidth('$888.88', font, font_size)
    tmpfile = tempfile.NamedTemporaryFile(delete=False, suffix='.pdf')

    #breaks string at word boundary which is less than max width in pixels
    def truncate_by_word( booktitle, max_width=0, split_char=' ' ):
        title_array = []
        for i in booktitle.split(split_char):
           title_array.append(i)
           if stringWidth(split_char.join(title_array), font, font_size) > max_width:
                title_array.pop()
                break
        return split_char.join(title_array)

    saleBanner=False
    if float(str(ourprice).strip('$')) < float(str(listprice).strip('$')):
        saleBanner=True
        doc_height = doc_height + font_size*1.5
        column_height = doc_height -2*margin

    canvas1 = canvas.Canvas(tmpfile, (doc_width, doc_height))
    #change coordinates so origin is now at left bottom margin corner
    canvas1.translate(margin, margin)
    canvas1.saveState()
    text_object = canvas1.beginText()
    text_object.setTextOrigin(0, column_height-margin)
    if saleBanner==True:
        text_object.setFont(font, font_size+2)
        text_object.textLine("SALE! SALE! SALE! SALE!")
    text_object.setFont(font, font_size)
    text_object.textOut( truncate_by_word(booktitle, max_width=(column_width - ourprice_width - margin)))
    text_object.moveCursor(column_width - ourprice_width, 0)
    text_object.textLine(str(format_ourprice))
    #move cursor permanently moves margin, so we have to move back to zero
    text_object.setXPos( -text_object.getX())
    text_object.textLine(truncate_by_word(author, max_width=column_width, split_char=','))
    canvas1.drawText(text_object)

    price_string='59999'
    if 0 <= float(str(ourprice).strip('$')) < 100:
        price_string='5' + ('%3.2f' % float(str(ourprice).strip('$'))).replace('.', '').zfill(4)[-4:]

    #create barcode and draw it at the origin.
    barcode1=barcode.createBarcodeDrawing('EAN13EXT5', value=str(isbn + price_string), validate=True, width= column_width, height=1.4*inch, humanReadable=True, fontName=font)
    renderPDF.draw(barcode1, canvas1, 0, 0)
    canvas1.restoreState()
    canvas1.showPage()
    canvas1.save()

    #print_command_string = string.Template(u"export TMPDIR=$tmpdir; $gs_location -q -dSAFER -dNOPAUSE -sDEVICE=pdfwrite -sourprice='$ourourprice' -sisbnstring='$isbn' -sbooktitle='$booktitle' -sauthorstring='$authorstring' -sOutputFile=%pipe%'lpr -P $printer -# $num_copies -o media=Custom.175x144' barcode_label.ps 1>&2")
    print(tmpfile.name)
    tmpfile.close()
    print_command_string = string.Template("lpr -P $printer -# $num_copies -o orientation-requested=3 -o media=60x60 $filename")
    #print_command_string = string.Template(u"open $filename")
    pcs_sub = print_command_string.substitute({'filename':tmpfile.name, 'printer': configuration.get('label_printer_name'), 'num_copies':num_copies})
    result=subprocess.call( ' '.join(pcs_sub.split()), shell=True)
    print(pcs_sub, file=sys.stderr)
def print_special_order_label(
    isbn="",
    booktitle="",
    author="",
    price=0,
    customer_name="",
    customer_phone="",
    customer_email="",
    copies=1,
):
    rl_config.warnOnMissingFontGlyphs = 1
    try:
        registerFont(TTFont("Courier New", "Courier New.ttf"))
        registerFont(TTFont("Courier New Bold", "Courier New Bold.ttf"))
        registerFont(TTFont("Courier New Italic", "Courier New Italic.ttf"))
        registerFont(TTFont("Courier New Bold Italic", "Courier New Bold Italic.ttf"))
        registerFontFamily(
            "Courier New",
            normal="Courier New",
            bold="Courier New Bold",
            italic="Courier New Italic",
            boldItalic="Courier New Bold Italic",
        )
    except TTFError:
        registerFont(TTFont("Courier New", "Courier_New.ttf"))
        registerFont(TTFont("Courier New Bold", "Courier_New_Bold.ttf"))
        registerFont(TTFont("Courier New Italic", "Courier_New_Italic.ttf"))
        registerFont(TTFont("Courier New Bold Italic", "Courier_New_Bold_Italic.ttf"))
        registerFontFamily(
            "Courier New",
            normal="Courier New",
            bold="Courier New Bold",
            italic="Courier New Italic",
            boldItalic="Courier New Bold Italic",
        )

    font = "Courier New Bold"
    font_size = 9
    format_price = "$" + ("%3.2f" % float(str(price).strip("$")))
    doc_width = 2.4 * inch
    doc_height = 4 * inch
    margin = 0.1 * inch
    column_width = doc_width - 2 * margin
    column_height = doc_height - 2 * margin
    second_field_margin = 0
    price_width = stringWidth("$888.88", font, font_size)
    debug = True
    tmpfile = tempfile.NamedTemporaryFile(delete=False)
    # breaks string at word boundary which is less than max width in pixels
    def truncate_by_word(booktitle, max_width=0, split_char=" "):
        title_array = []
        for i in booktitle.split(split_char):
            title_array.append(i)
            if (
                stringWidth(string.join(title_array, split_char), font, font_size)
                > max_width
            ):
                title_array.pop()
                break
        return string.join(title_array, split_char)

    canvas1 = canvas.Canvas(tmpfile, (doc_width, doc_height))
    # change coordinates so origin is now at left bottom margin corner
    canvas1.translate(margin, margin)
    # create barcode and draw it at the origin.
    price_string = "5999"
    if 0 <= float(str(price).strip("$")) < 100:
        price_string = (
            "5"
            + ("%3.2f" % float(str(price).strip("$"))).replace(".", "").zfill(4)[-4:]
        )
    barcode1 = barcode.createBarcodeDrawing(
        "EAN13",
        value=str(isbn + price_string),
        validate=True,
        width=column_width,
        height=1.4 * inch,
        humanReadable=True,
        fontName=font,
    )
    renderPDF.draw(barcode1, canvas1, 0, 0)

    text_object = canvas1.beginText()
    text_object.setFont(font, font_size)
    text_object.setTextOrigin(0, column_height - margin)
    text_object.textOut(
        truncate_by_word(booktitle, max_width=(column_width - price_width - margin))
    )
    text_object.moveCursor(column_width - price_width, 0)
    text_object.textLine(str(format_price))
    # move cursor permanently moves margin, so we have to move back to zero
    text_object.setXPos(-text_object.getX())
    text_object.textLine(
        truncate_by_word(author, max_width=column_width, split_char=",")
    )
    text_object.textLine("")
    text_object.textLine("On hold since %s for:" % strftime("%m/%d/%Y"))
    text_object.textLine(customer_name)
    if customer_phone:
        text_object.textOut("Phone:")
        text_object.moveCursor(45, 0)
        text_object.textLine(customer_phone)
    if customer_email:
        # move cursor permanently moves margin, so we have to move back to zero
        text_object.setXPos(-text_object.getX())
        text_object.textOut("E-mail:")
        text_object.moveCursor(45, 0)
        text_object.textLine(customer_email)
    text_object.setXPos(-text_object.getX())
    text_object.textLine("")
    for i in ("First", "Second", "Third"):
        text_object.textLine("□ %s call on ___ by ___" % i)
    text_object.textLine("")
    text_object.textLine("Notes:")
    canvas1.drawText(text_object)
    canvas1.showPage()
    canvas1.save()

    # print_command_string = string.Template(u"export TMPDIR=$tmpdir; $gs_location -q -dSAFER -dNOPAUSE -sDEVICE=pdfwrite -sprice='$ourprice' -sisbnstring='$isbn' -sbooktitle='$booktitle' -sauthorstring='$authorstring' -sOutputFile=%pipe%'lpr -P $printer -# $num_copies -o media=Custom.175x120' barcode_label.ps 1>&2")
    tmpfile.close()
    print_command_string = string.Template(
        "lpr -P $printer -# $numcopies -o orientation-requested=3 -o media=BrL063E078A5766 $filename"
    )
    pcs_sub = print_command_string.substitute(
        {
            "filename": tmpfile.name,
            "printer": configuration.get("label_printer_name"),
            "numcopies": copies,
        }
    )
    subprocess.check_call(
        pcs_sub.encode("utf8"),
        shell=True,
        cwd=os.path.dirname(os.path.abspath(__file__)),
    )
import isbnlib

from amzsear import AmzSear

import sys
import re

from urllib.error import HTTPError
import requests
from bs4 import BeautifulSoup

from sqlobject.sqlbuilder import Field, RLIKE, AND, OR, LEFTJOINOn
from MySQLdb import escape_string

use_amazon_ecs = configuration.get("use_amazon_ecs")
amazon_license_key = configuration.get("amazon_license_key")
amazon_secret_key = configuration.get("amazon_secret_key")
amazon_associate_tag = configuration.get("amazon_associate_tag")
default_kind = configuration.get("default_kind")
internal_isbn_prefix = configuration.get("internal_isbn_prefix")

# so we're monkeypatching isbnlib to also accept ourinternal isbns
isbn13_regex_template = '%s{1}(?:-?\d){10,16}|%s{1}[- 0-9]{10,16}'
isbn_prefixes = ['97[89]',]
if internal_isbn_prefix:
    isbn_prefixes.append(internal_isbn_prefix)
isbn13_regex = [isbn13_regex_template % (x, x) for x in isbn_prefixes]
isbn13_regex = '|'.join(isbn13_regex)
isbn13_regex = re.compile(isbn13_regex, re.I)
from inventoryserver.server import SpecialOrders

# cherrypy.config.update({'environment': 'embedded'})

if cherrypy.__version__.startswith("3.0") and cherrypy.engine.state == 0:
    cherrypy.engine.start(blocking=False)
    atexit.register(cherrypy.engine.stop)


class Root(object):
    def index(self):
        return "Hello World!"

    index.exposed = True


root = InventoryServer()
root.admin = Admin()
root.staffing = Staffing()
root.notes = Noteboard()
root.register = Register()
root.specialorder = SpecialOrders()

cherrypy_local_config_file = configuration.get("cherrypy_local_config_file")
application = cherrypy.Application(
    root, script_name=None, config=cherrypy_local_config_file
)

if __name__ == "__main__":
    cherrypy.quickstart(root, "/", cherrypy_local_config_file)