Exemplo n.º 1
0
 def __init__(self, encode=None, **kwargs):
     BasePrint.__init__(self, **kwargs)
     from escpos.printer import Dummy
     self.dummy = Dummy()
     if encode:
         self.dummy.codepage = encode
     self.dummy.hw('init')
     self.texts = []
def test_type_of_object_passed_to_image_function(img_function):
    """
    Test the type of object that is passed to the image function during non-native qr-printing.

    The type should be PIL.Image
    """
    d = Dummy()
    d.qr("LoremIpsum")
    args, kwargs = img_function.call_args
    assert isinstance(args[0], Image.Image)
Exemplo n.º 3
0
def test_line_spacing_error_handling():
    printer = Dummy()
    with assert_raises(ValueError):
        printer.line_spacing(99, divisor=44)
    with assert_raises(ValueError):
        printer.line_spacing(divisor=80, spacing=86)
    with assert_raises(ValueError):
        printer.line_spacing(divisor=360, spacing=256)
    with assert_raises(ValueError):
        printer.line_spacing(divisor=180, spacing=256)
Exemplo n.º 4
0
def main():
    imageIn = sys.argv[1]
    fileOut = imageIn + "_tmp.txt"

    p = Dummy()
    p.image(imageIn)
    f = File(fileOut)
    f._raw(p.output)
    f.cut()

    subprocess.call("lpr -P THERMAL -o raw " + fileOut, shell=True)

    os.remove(fileOut)
Exemplo n.º 5
0
def test_line_spacing_error_handling():
    printer = Dummy()
    with assert_raises(ValueError):
      printer.line_spacing(99, divisor=44)
    with assert_raises(ValueError):
      printer.line_spacing(divisor=80, spacing=86)
    with assert_raises(ValueError):
      printer.line_spacing(divisor=360, spacing=256)
    with assert_raises(ValueError):
      printer.line_spacing(divisor=180, spacing=256)
Exemplo n.º 6
0
def test_printit_random_scales_sanity_check(scale, client):
    printer = Dummy()
    ticket = 'TESTING100'
    office = 'TESTING_OFFICE'
    tickets_ahead = 'TESTING300'
    task = 'TESTING_TASK_NAME'
    current_ticket = 'TESTING200'
    site = 'www.testing.com'
    language = 'en'
    number_of_saperators = 2

    ticket_content = printit(printer, ticket, office, tickets_ahead, task,
                             current_ticket, site, language, scale)\
                        .output\
                        .decode('utf-8')

    assert 'FQM\n' in ticket_content
    assert f'\n{site}\n' in ticket_content
    assert f'\n{ticket}\n' in ticket_content
    assert f'\nOffice : {office}\n' in ticket_content
    assert f'\nCurrent ticket : {current_ticket}\n' in ticket_content
    assert f'\nTickets ahead : {tickets_ahead}\n' in ticket_content
    assert f'\nTask : {task}\n' in ticket_content
    assert f'\nTime : {datetime.now().__str__()[:-7]}\n' in ticket_content
    assert ticket_content.count(f'\n{"-" * 15}\n') == number_of_saperators
Exemplo n.º 7
0
    def SnapAndPrint(self):
        subprocess.run(PIC_COMMAND.split(" ")) 
        dummy = Dummy()
        
        dummy.text("\n\n\nBravoLT - GRPS - 2019\n\n\n")
        dummy.image("out.jpg")
        dummy.text("\n\n\nBravoLT - GRPS - 2019")

        self.printer._raw(dummy.output)
Exemplo n.º 8
0
def print_ticket_cli(printer,
                     ticket,
                     office,
                     tickets_ahead,
                     task,
                     current_ticket,
                     host='localhost',
                     language='en',
                     scale=1,
                     windows=False,
                     unix=False):
    '''Print a ticket through the Command-Line interface.

    Parameters
    ----------
    printer : str
        the printer name.
    ticket : int
        ticket number.
    office : str
        office number and prefix.
    tickets_ahead : int
        number of tickets ahead.
    task : str
        task's name.
    current_ticket : int
        current ticket in the queue.
    host : str, optional
        host to find printer on, by default 'localhost'
    language : str, optional
        printing language, by default 'en'
    scale : int, optional
        ticket font scale, by default 1
    windows : bool, optional
        if printing on Windows, by default False
    unix : bool, optional
        if printing on Unix-like, by default False
    '''
    ticket_content = printit(Dummy(),
                             ticket,
                             office,
                             tickets_ahead,
                             task,
                             current_ticket,
                             lang=language,
                             scale=scale).output
    file_path = path.join(getcwd(),
                          f'{uuid.uuid4()}'.replace('-', '') + '.txt')

    with open(file_path, 'wb+') as file:
        file.write(ticket_content)

    if unix:
        system(f'lp -d "{printer}" -o raw "{file_path}"')
    elif windows:
        system(f'print /D:\\\{host}\\"{printer}" "{file_path}"')

    if path.isfile(file_path):
        remove(file_path)
Exemplo n.º 9
0
def print_ticket_windows(pname, a, b, c, d, cit, ip, l='en', scale=1):
    content = printit(Dummy(), a, b, c, d, cit, lang=l, scale=scale).output
    file_path = path.join(getcwd(),
                          f'{uuid.uuid4()}'.replace('-', '') + '.txt')

    with open(file_path, 'wb+') as file:
        file.write(content)

    system(f'print /D:\\\localhost\\"{pname}" "{file_path}"')
    path.isfile(file_path) and remove(file_path)
Exemplo n.º 10
0
def printwin(pname, a, b, c, d, cit, l, ip):
    outp = printit(Dummy(), a, b, c, d, cit, lang=l)
    outp = outp.output
    fname = "dummy.txt"
    ffname = path.join(getcwd(), fname)
    f = open(ffname, 'w')
    f.write(outp)
    f.close()
    lh = ip
    txt = 'print /D:\\\%s\\"%s" "%s"' % (lh, pname, ffname)
    system(txt)
    if path.isfile(ffname):
        remove(ffname)
Exemplo n.º 11
0
            reserveringTeken + " " + str(reservering['numberOfPeople']) +
            "p om " + reserveringTijd + " - " + reserveringNaam
        })

        for ticket in reservering['tickets']:
            if ticket["title"] == "High Tea":
                reserveringPrinten.append({"opmerking": "^^ High Tea"})

        aantalReserveringen += 1

if reserveringPrinten:

    logging.debug('%s reserveringen worden geprint', aantalReserveringen)

    kitchen = Network(os.getenv("IP_PRINTER"))  #Printer IP Address
    output = Dummy()

    output.text("Reservering Update (" + tijdVandaagPrint + " " +
                datumVandaagPrint + ")\n\n")

    # Maak tekst zwart
    output._raw(b'\x1B\x35' + b'\x01')

    for reserveringPrint in reserveringPrinten:

        if reserveringPrint.get("bericht"):
            output.text(reserveringPrint.get("bericht") + "\n")

        if reserveringPrint.get("opmerking"):
            # Maak tekst rood
            output._raw(b'\x1B\x34' + b'\x01')
Exemplo n.º 12
0
def instance():
    return Dummy()
Exemplo n.º 13
0
def driver():
    return Dummy()
Exemplo n.º 14
0
    def __init__(self, uid, pid):
        self.p = Dummy()

        self.qanswered = 0
        self.id = uid
        self.pid = pid
Exemplo n.º 15
0
def test_block_text():
    printer = Dummy()
    printer.block_text(
        "All the presidents men were eating falafel for breakfast.", font='a')
    assert printer.output == \
        b'All the presidents men were eating falafel\nfor breakfast.'
Exemplo n.º 16
0
 def prints(self, code, align='left', qty=1):
     p_conf = settings.PRINTER_CONF
     usb_conf = p_conf['usb_conf']
     printer = Usb(usb_conf['vendor_id'], usb_conf['product_id'],
                   usb_conf['timeout'], usb_conf['input_endpoint'],
                   usb_conf['output_endpoint'])
     dummy = Dummy()
     if align.upper() == "LEFT":
         dummy._raw(TXT_ALIGN_LT)
     else:
         dummy._raw(TXT_ALIGN_RT)
     dummy._raw(PD_P50)
     dummy._raw(BARCODE_HEIGHT + six.int2byte(120))
     dummy._raw(BARCODE_WIDTH + six.int2byte(2))
     dummy._raw(BARCODE_FONT_A)
     dummy._raw(BARCODE_TXT_BLW)
     dummy._raw(_SET_BARCODE_TYPE(2))
     dummy._raw(code.encode())
     printer._raw(dummy.output)
     printer._raw(NUL)
Exemplo n.º 17
0
    def __init__(self):
        from escpos.printer import Usb, Dummy

        self.eps = Usb(0x4b8, 0x0e03)
        self.dps = Dummy()
Exemplo n.º 18
0
    def test_print():

        global pos

        pos.close()

        dp = Dummy()

        bold_emphasis = b"\x1b\x21\x08"  # Sets text to bold
        second_typeface_emphasis = b"\x1b\x21\x01"  # Selects font B (different code to actual font size stuff)
        reset_emphasis = b"\x1b\x21\x00"  # Reset emphasis
        font_size_2x = b"\x1d\x21\x10"  # Change text size to 2x
        font_reset = b"\x1d\x21\x00"  # Reset text size

        dp.text("Test print\n\n")

        dp._raw(reset_emphasis)
        dp._raw(font_size_2x)
        dp.text("Font size two" + "\n")
        dp._raw(font_reset)

        dp._raw(second_typeface_emphasis)
        dp.text("Typeface two\n")
        dp._raw(reset_emphasis)

        dp._raw(bold_emphasis)
        dp.text("Bold text\n")
        dp._raw(reset_emphasis)

        dp.text("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!\"£$%^&*()-=_+[]{}'#@~;:<>?,./\\|'")

        dp.cut()

        test_handle = None

        test_handle = PosPrinter(int("0x" + SettingsUi.printProductIDLine.text(), base=16),
                                 int("0x" + SettingsUi.printVendorIDLine.text(), base=16),
                                 test_mode=True)

        if test_handle.failed:
            return

        test_handle.print(dp.output)
        test_handle.close()

        pos.reset()

        popup_message("Test printed!")
Exemplo n.º 19
0
def get_printer():
    return Dummy(magic_encode_args={'disabled': True, 'encoding': 'CP437'})
Exemplo n.º 20
0
    def print_ticket(self, order):
        self.d = Dummy()
        self.d.line_spacing(120)
        self.d.ln(1)

        self.d.set(align="center",
                   bold=True,
                   underline=2,
                   double_height=False,
                   double_width=False,
                   custom_size=True,
                   smooth=True,
                   width=2,
                   height=2,
                   invert=False,
                   density=8,
                   font='a')
        self.d.block_text(str(order.order_number) + ' ' + order.name + '\n',
                          font='a')
        self.d.ln(1)

        self.d.set(align="center",
                   bold=False,
                   underline=0,
                   double_height=False,
                   double_width=False,
                   custom_size=True,
                   smooth=True,
                   width=2,
                   height=2,
                   invert=False,
                   density=8,
                   font='a')
        self.d.block_text(order.order_type + '\n', columns=20, font='a')
        self.d.ln(1)

        self.d.text(order.formatted_number + '\n')
        self.d.text(order.date + '\n')
        self.d.text(order.time + '\n')
        self.d.text(' \n')

        self.d.set(align="left",
                   bold=True,
                   underline=0,
                   double_height=False,
                   double_width=False,
                   custom_size=True,
                   smooth=True,
                   width=2,
                   height=2,
                   invert=False,
                   density=8,
                   font='b')
        self.d.text('PICKUP TIME\n')

        self.d.set(align="left",
                   bold=False,
                   underline=0,
                   double_height=False,
                   double_width=False,
                   custom_size=True,
                   smooth=True,
                   width=2,
                   height=2,
                   invert=False,
                   density=8,
                   font='a')
        self.d.block_text(order.pickup_time + '\n', columns=20, font='a')

        self.d.ln(2)

        self.d.set(align="left",
                   bold=True,
                   underline=0,
                   double_height=False,
                   double_width=False,
                   custom_size=True,
                   smooth=True,
                   width=2,
                   height=2,
                   invert=False,
                   density=8,
                   font='b')
        self.d.text('ORDER\n')

        self.d.set(align="left",
                   bold=False,
                   underline=0,
                   double_height=False,
                   double_width=False,
                   custom_size=True,
                   smooth=True,
                   width=2,
                   height=2,
                   invert=False,
                   density=8,
                   font='a')
        self.d.block_text(order.order + '\n', columns=20, font='a')

        self.d.ln(2)

        if order.notes != '':
            self.d.set(align="left",
                       bold=True,
                       underline=0,
                       double_height=False,
                       double_width=False,
                       custom_size=True,
                       smooth=True,
                       width=2,
                       height=2,
                       invert=False,
                       density=8,
                       font='b')
            self.d.text('NOTES\n')

            self.d.set(align="left",
                       bold=False,
                       underline=0,
                       double_height=False,
                       double_width=False,
                       custom_size=True,
                       smooth=True,
                       width=2,
                       height=2,
                       invert=False,
                       density=8,
                       font='a')
            self.d.block_text(order.notes + '\n', columns=20, font='a')

        self.d.cut()
Exemplo n.º 21
0
def print_ticket_windows_ar(pname, ti, ofc, tnu, tas, cticket, ip, l=None):
    def fsizeit(text, t, f):
        return f.getsize(t)

    def center(text, t, f):
        fs1, fs2 = fsizeit(text, t, f)
        return ((text.size[0] - fs1) / 2, (text.size[1] - fs2) / 2)

    if name == 'nt':
        fpath = absolute_path('static\\gfonts\\arial.ttf')
    else:
        fpath = absolute_path('static/gfonts/arial.ttf')
    fonts = [
        ImageFont.truetype(fpath, 50),
        ImageFont.truetype(fpath, 30),
        ImageFont.truetype(fpath, 25)
    ]

    logo = 'FQM ' + VERSION[:4]
    title = u'نظام إدارة الحشود الحر'
    title = arabic_reshaper.reshape(title)
    title = get_display(title)
    link = 'http://fqms.github.io'
    border = "#" * 20
    ticket = str(ti)
    officet = u'المكتب : ' + ofc
    office = arabic_reshaper.reshape(officet)
    office = get_display(office)
    try:
        taskt = u'المهمة : ' + tas
    except Exception:
        taskt = tas
    task = arabic_reshaper.reshape(taskt)
    task = get_display(task)
    datet = u'الوقت : '
    datet += str(datetime.now())[:-7]
    date = arabic_reshaper.reshape(datet)
    date = get_display(date)
    aheadt = u'تذاكر قبلك : '
    aheadt += str(tnu)
    ahead = arabic_reshaper.reshape(aheadt)
    ahead = get_display(ahead)
    cutit = u'التذكرة الحالية : '
    cutit += str(cticket)
    cuti = arabic_reshaper.reshape(cutit)
    cuti = get_display(cuti)

    w = 400
    bt_1 = Image.new('RGB', (w, 60), "white")
    bt_2 = Image.new('RGB', (w, 60), "white")
    bt_3 = Image.new('RGB', (w, 60), "white")
    st_1 = Image.new('RGB', (w, 50), "white")
    st_2 = Image.new('RGB', (w, 50), "white")
    st_3 = Image.new('RGB', (w, 50), "white")
    st_4 = Image.new('RGB', (w, 50), "white")
    st_5 = Image.new('RGB', (w, 50), "white")
    st_6 = Image.new('RGB', (w, 50), "white")
    st_7 = Image.new('RGB', (w, 50), "white")
    st_8 = Image.new('RGB', (w, 50), "white")
    tt = 50 * 8
    tt += 60 * 3
    mt = Image.new('RGB', (w, tt), "white")

    bd_1 = ImageDraw.Draw(bt_1)
    bd_2 = ImageDraw.Draw(bt_2)
    bd_3 = ImageDraw.Draw(bt_3)
    sd_1 = ImageDraw.Draw(st_1)
    sd_2 = ImageDraw.Draw(st_2)
    sd_3 = ImageDraw.Draw(st_3)
    sd_4 = ImageDraw.Draw(st_4)
    sd_5 = ImageDraw.Draw(st_5)
    sd_6 = ImageDraw.Draw(st_6)
    sd_7 = ImageDraw.Draw(st_7)
    sd_8 = ImageDraw.Draw(st_8)
    md = ImageDraw.Draw(mt)

    b = "black"
    bd_1.text(center(bt_1, logo, fonts[0]), logo, font=fonts[0], fill=b)
    bd_2.text(center(bt_2, title, fonts[1]), title, font=fonts[1], fill=b)
    bd_3.text(center(bt_3, ticket, fonts[0]), ticket, font=fonts[0], fill=b)
    sd_1.text(center(st_1, link, fonts[2]), link, font=fonts[2], fill=b)
    sd_2.text(center(st_2, border, fonts[2]), border, font=fonts[2], fill=b)
    sd_3.text(center(st_3, border, fonts[2]), border, font=fonts[2], fill=b)
    sd_4.text(center(st_4, office, fonts[2]), office, font=fonts[2], fill=b)
    sd_5.text(center(st_5, task, fonts[2]), task, font=fonts[2], fill=b)
    sd_6.text(center(st_6, date, fonts[2]), date, font=fonts[2], fill=b)
    sd_7.text(center(st_7, ahead, fonts[2]), ahead, font=fonts[2], fill=b)
    sd_8.text(center(st_8, cuti, fonts[2]), cuti, font=fonts[2], fill=b)

    tts = 0
    mt.paste(bt_1, (0, 0))
    tts += bt_1.size[1]
    mt.paste(bt_2, (0, tts))
    tts += bt_2.size[1]
    mt.paste(st_1, (0, tts))
    tts += st_1.size[1]
    mt.paste(st_2, (0, tts))
    tts += st_2.size[1]
    mt.paste(bt_3, (0, tts))
    tts += bt_3.size[1]
    mt.paste(st_3, (0, tts))
    tts += st_3.size[1]
    mt.paste(st_4, (0, tts))
    tts += st_4.size[1]
    mt.paste(st_8, (0, tts))
    tts += st_8.size[1]
    mt.paste(st_7, (0, tts))
    tts += st_7.size[1]
    mt.paste(st_5, (0, tts))
    tts += st_5.size[1]
    mt.paste(st_6, (0, tts))

    sffs = []
    sfs = [
        f'{uuid.uuid4()}'.replace('-', '') + '.jpg',
        f'{uuid.uuid4()}'.replace('-', '') + '.txt'
    ]

    for f in sfs:
        sffs.append(path.join(getcwd(), f))
    mt.save(sfs[0], format="JPEG")
    p = Dummy()
    p.image(sfs[0], fragment_height=tt, high_density_vertical=True)
    p.cut()
    f = open(sfs[1], 'wb+')
    f.write(p.output)
    p.close()
    f.close()

    text = f'print /D:\\\localhost\\"{pname}" "{sfs[1]}"'
    system(text)
    for f in sffs:
        if path.isfile(f):
            remove(f)
Exemplo n.º 22
0
def test_line_spacing_code_gen():
    printer = Dummy()
    printer.line_spacing(10)
    assert printer.output == b'\x1b3\n'
import os
from queue import Queue
from threading import Thread

from dotenv import load_dotenv
from escpos.printer import Dummy, Usb
import escpos.constants

load_dotenv()
DRY_RUN = False

if DRY_RUN:
    printer = Dummy()
else:
    printer = Usb(int(os.getenv("VENDOR_ID"), base=16),
                  int(os.getenv("PRODUCT_ID"), base=16),
                  in_ep=int(os.getenv("IN_ENDPOINT"), base=16),
                  out_ep=int(os.getenv("OUT_ENDPOINT"), base=16))


class PrinterDaemon(Thread):
    def __init__(self):
        super().__init__()
        self.print_queue = Queue()

    def run(self) -> None:
        while True:
            to_print = self.print_queue.get()
            if not DRY_RUN:
                printer.open()
            printer._raw(to_print)
Exemplo n.º 24
0
def test_line_spacing_rest():
    printer = Dummy()
    printer.line_spacing()
    assert printer.output == b'\x1b2'
Exemplo n.º 25
0
    def post(self, request):
        sale_form = SaleFormSet(request.POST, prefix="sale")

        # ======================================
        # Get investor who buy this checkout
        # ======================================
        investor_id = request.POST.get('investor', '')
        if investor_id == "":
            investor_id = 0
        investor = Investor.objects.filter(id=investor_id).first()
        if investor:
            buyer = investor.created_by
        # if buyer is not an investor, set buyer to id 0
        else:
            buyer = User.objects.filter(id=0).first()
            if not buyer:
                buyer = User(id=0,
                             username="******",
                             email="*****@*****.**",
                             first_name="None")
                buyer.save()
        # ======================================

        is_checkout = False
        parameter = request.POST.get("parameter")

        # ======================================
        # If checkhout finished, we add all the item in cart to checkout table
        # ======================================
        if parameter == "checkout":
            is_checkout = True

            if request.POST.get("price") != "" and request.POST.get(
                    "paid") != "":
                checkout = Checkout(
                    price=request.POST.get("price"),
                    paid=request.POST.get("paid"),
                    created_by=buyer,
                    sale_by=request.user,
                )
                checkout.save()
            else:
                is_checkout = False
                parameter = "hold"
        # ======================================

        # ======================================
        # For every item in sale form, we add it into table
        # ======================================
        item_sale_text = ""
        item_sale_discount_text = ""
        item_sale_amout = 0
        item_sale_discount_amout = 0
        item_sale_cashback_amout = 0
        for s in sale_form:
            if s.is_valid() and len(s.cleaned_data) > 0:
                product = Product.objects.filter(
                    id62=s.cleaned_data['product_id62']).first()
                item_sale = Sale(
                    product=product,
                    amount=int(s.cleaned_data['quantity']) *
                    int(s.cleaned_data['price'].replace(",", "")),
                    qty=int(s.cleaned_data['quantity']),
                    price=int(s.cleaned_data['price'].replace(",", "")),
                    created_by=buyer,
                    sale_by=request.user,
                )
                if product.applied_discount():
                    item_sale.discount = product.applied_discount()
                if is_checkout:
                    item_sale.status = 4
                    item_sale.checkout = checkout
                    item_sale.save()
                    cashback = item_sale.sold(request.user, buyer)
                    product.sale(int(s.cleaned_data['quantity']))

                    item_sale_amout += item_sale.amount
                    item_sale_text += "%s    @%d   x%d   %d\n" % (
                        product.display_name, item_sale.price, item_sale.qty,
                        item_sale.amount)
                    item_sale_cashback_amout += cashback
                    if product.applied_discount():
                        amount_discounted = item_sale.qty * (
                            item_sale.price - item_sale.discounted_price)
                        item_sale_discount_text += "%s       %d%%   %d\n" % (
                            product.display_name, item_sale.discount.reduction,
                            amount_discounted)
                        item_sale_discount_amout += amount_discounted
                else:
                    if parameter == "cancel":
                        item_sale.status = 2
                    if parameter == "hold":
                        item_sale.status = 3
                    item_sale.save()
            else:
                print s.errors
        # ======================================

        p_conf = settings.PRINTER_CONF
        if is_checkout and p_conf['print_on']:
            usb_conf = p_conf['usb_conf']
            printer = Usb(usb_conf['vendor_id'], usb_conf['product_id'],
                          usb_conf['timeout'], usb_conf['input_endpoint'],
                          usb_conf['output_endpoint'])

            receipt = Dummy()
            receipt.set(height=2, align='center', text_type="B")
            receipt.text('Koperasi Warung Kita Untuk Kita\n')
            receipt.set(align='center')
            receipt.text('Tanggal: %s - Pukul: %s\n' %
                         (datetime.datetime.now().strftime("%d-%m-%Y"),
                          datetime.datetime.now().strftime("%H:%M")))
            receipt.text('==============================================\n\n')
            receipt.set(align='right')
            receipt.text(item_sale_text)
            receipt.text('============================\n')
            receipt.text('Total :      Rp. %d\n\n' % item_sale_amout)
            if item_sale_discount_amout > 0:
                receipt.set(align='center')
                receipt.text('Diskon\n')
                receipt.set(align='right')
                receipt.text(item_sale_discount_text)
                receipt.text('============================\n')
                receipt.text('Total Diskon:      Rp.%d\n\n' %
                             item_sale_discount_amout)

            receipt.set(text_type="B", align="right")
            receipt.text('Total Harga :      Rp.%d\n' % item_sale_amout)
            if item_sale_discount_amout > 0:
                receipt.text('- Rp.%d\n' % item_sale_discount_amout)
                receipt.text('(Rp.%d)\n' %
                             (item_sale_amout - item_sale_discount_amout))
            receipt.text('Bayar :      Rp.%s\n' % checkout.paid)
            receipt.text('Kembalian :      Rp.%d\n\n\n' %
                         (int(checkout.paid) -
                          (item_sale_amout - item_sale_discount_amout)))

            receipt.set(height=2, align='center', text_type="B")
            if buyer.id > 0:
                receipt.text('%s %s\nTerimakasih Telah Berbelanja\n\n' %
                             (buyer.first_name, buyer.last_name))
                receipt.text('Anda Mendapatkan Cashback Sebesar Rp.%d' %
                             item_sale_cashback_amout)
            else:
                receipt.text('Terimakasih Telah Berbelanja')

            if p_conf['cut_paper']:
                receipt.cut()

            if p_conf['kick_drawer']:
                receipt.cashdraw(2)

            printer._raw(receipt.output)

        return redirect(reverse("core:sale"))
Exemplo n.º 26
0
    def slotekstre(self, item):
        if self.kontrol==0:
            print " kasa"
        myddb1 = Myddb()
        self.d = Dummy()
        self.d.text(chr(27))
        self.d.text(chr(116))
        self.d.text(chr(61))

        self.kontrol = 1
        self.d.set(font='a', align='left', height=2, width=1)

        print "ekstrerapor"
        self.tableWidget.clearContents()
        self.tableWidget.setColumnWidth(0, 150)
        self.tableWidget.setColumnWidth(1, 100)
        self.tableWidget.setColumnWidth(2, 75)
        self.tableWidget.setColumnWidth(3, 75)
        self.tableWidget.setColumnWidth(4, 75)
        self.tableWidget.setColumnWidth(5, 75)

        deger1 = self.dateEdit.date().toPyDate()
        deger2 = self.dateEdit_2.date().toPyDate()
        tar1 = deger1.strftime('%d_%m_%Y')
        tar2 = deger2.strftime('%d_%m_%Y')
        self.d.text("  " + tar1 + "  " + tar2 + " Kasa Raporu " + " \n\n")

        self.wb = xlwt.Workbook(encoding="utf-8")
        self.dest_filename = "EKSTRE" + tar1 + tar2 + ".xls"
        date_format = xlwt.XFStyle()
        date_format.num_format_str = u'#,##0.00₺'
        date_xf = xlwt.easyxf(num_format_str='DD/MM/YYYY')
        self.ws1 = self.wb.add_sheet("ekstre")
        self.style1 = xlwt.easyxf('pattern: pattern solid, fore_colour red;')

        c = canvas.Canvas("EKSTRE" + tar1 + tar2 + ".pdf")
        pdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf'))
        c.setFont("Verdana", 8)

        item = "         FİŞ NO       TARİH                AÇIKLAMA                             BORÇ                  ALACAK                    BAKİYE                      "
        c.drawString(10, 810, item)
        tar1 = deger1.strftime('%Y-%m-%d')
        tar2 = deger2.strftime('%Y-%m-%d')

        sql = """select kasano,sum(tutar) from kasa where date(tarih) between %s and %s  group by kasano; """

        bul2 = myddb1.cur.execute(sql, (tar1, tar2))
        print bul2, tar1, tar2

        bul = myddb1.cur.fetchall()
        i = bul2
        j = 5
        self.tableWidget.setRowCount(i+5)
        aa = 0
        bb = 0
        dep=0
        toplam = 0.0
        toplam1 = 0.0
        toplam2 = 0.0000
        for row1 in bul:


            if row1[0]==100:
                item = str(row1[0])+" Nakit "
                self.ws1.write(aa, 0, item)
                self.tableWidget.setItem(aa, 0, QtGui.QTableWidgetItem(item))
                c.drawString(150, 800 - (15 * (bb + 1)), item)
                self.d.text(item.ljust(30) + " ")
                item = str(row1[1])
                self.d.text(item.rjust(10) + " \n")
                self.ws1.write(aa, 3, float(row1[1]))
                c.drawRightString(310, 800 - (15 * (bb + 1)), item)
                toplam = Decimal(toplam) + (row1[1])

                toplam1 = Decimal(toplam1) + (row1[1])
                item=QtGui.QTableWidgetItem(item)
                item.setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignRight)
                self.tableWidget.setItem(aa, 1, item)

                item= ""
                c.drawRightString(390, 800 - (15 * (bb + 1)), item)
                self.tableWidget.setItem(aa, 2, QtGui.QTableWidgetItem(item))


            if row1[0]==101:
                item = str(row1[0]) + " Indirim "
                self.ws1.write(aa, 0, item)
                self.tableWidget.setItem(aa, 0, QtGui.QTableWidgetItem(item))
                c.drawString(150, 800 - (15 * (bb + 1)), item)
                self.d.text(item.ljust(30) + " ")

                item = str(row1[1])
                self.d.text(item.rjust(10) + " \n")
                self.ws1.write(aa, 3, float(row1[1]))
                c.drawRightString(310, 800 - (15 * (bb + 1)), item)

                self.tableWidget.setItem(aa, 1, QtGui.QTableWidgetItem(item))
                item = ""
                c.drawRightString(390, 800 - (15 * (bb + 1)), item)
                self.tableWidget.setItem(aa, 2, QtGui.QTableWidgetItem(item))

            if row1[0]==102:
                item = str(row1[0])+" Servis "
                self.ws1.write(aa, 0, item)
                self.tableWidget.setItem(aa, 0, QtGui.QTableWidgetItem(item))
                c.drawString(150, 800 - (15 * (bb + 1)), item)
                self.d.text(item.ljust(30) + " ")

                item = str(row1[1])
                self.d.text(item.rjust(10)+ " \n")
                self.ws1.write(aa, 3, float(row1[1]))
                c.drawRightString(310, 800 - (15 * (bb + 1)), item)
                toplam = Decimal(toplam) - (row1[1])
                self.tableWidget.setItem(aa, 1, QtGui.QTableWidgetItem(item))
                item= ""
                c.drawRightString(390, 800 - (15 * (bb + 1)), item)
                self.tableWidget.setItem(aa, 2, QtGui.QTableWidgetItem(item))

            if row1[0]==105:
                item = str(row1[0])+" Denizbank "
                self.ws1.write(aa, 0, item)
                self.tableWidget.setItem(aa, 0, QtGui.QTableWidgetItem(item))
                c.drawString(150, 800 - (15 * (bb + 1)), item)
                self.d.text(item.ljust(30) + " ")

                item = str(row1[1])
                self.ws1.write(aa, 3, float(row1[1]))
                c.drawRightString(310, 800 - (15 * (bb + 1)), item)
                toplam2=Decimal(toplam2)+(row1[1])
                toplam1 = Decimal(toplam1) + (row1[1])
                self.tableWidget.setItem(aa, 1, QtGui.QTableWidgetItem(item))
                self.d.text(item.rjust(10)+ " \n")
                self.tableWidget.item(aa, 1).setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignRight)

                item= ""
                c.drawRightString(390, 800 - (15 * (bb + 1)), item)
                self.tableWidget.setItem(aa, 2, QtGui.QTableWidgetItem(item))

            if row1[0]==106:
                item = str(row1[0])+" Yapi Kredi "
                self.ws1.write(aa, 0, item)
                self.d.text(item.ljust(30) + " ")
                self.tableWidget.setItem(aa, 0, QtGui.QTableWidgetItem(item))
                c.drawString(150, 800 - (15 * (bb + 1)), item)

                item = str(row1[1])
                self.d.text(item.rjust(10)+ " \n")
                self.ws1.write(aa, 3, float(row1[1]))
                c.drawRightString(310, 800 - (15 * (bb + 1)), item)
                toplam2=Decimal(toplam2)+(row1[1])
                toplam1 = Decimal(toplam1) + (row1[1])
                self.tableWidget.setItem(aa, 1, QtGui.QTableWidgetItem(item))
                item= ""
                c.drawRightString(390, 800 - (15 * (bb + 1)), item)
                self.tableWidget.setItem(aa, 2, QtGui.QTableWidgetItem(item))

            if row1[0]==111:
                item = str(row1[0])+" Harcamalar "
                self.ws1.write(aa, 0, item)
                self.d.text(item.ljust(30) + " ")
                self.tableWidget.setItem(aa, 0, QtGui.QTableWidgetItem(item))
                c.drawString(150, 800 - (15 * (bb + 1)), item)

                item = str(row1[1])
                self.d.text(item.rjust(10)+ " \n")
                self.ws1.write(aa, 3, float(row1[1]))
                c.drawRightString(310, 800 - (15 * (bb + 1)), item)
                toplam = Decimal(toplam) + (row1[1])
                self.tableWidget.setItem(aa, 1, QtGui.QTableWidgetItem(item))
                item= ""
                c.drawRightString(390, 800 - (15 * (bb + 1)), item)
                self.tableWidget.setItem(aa, 2, QtGui.QTableWidgetItem(item))





            aa = aa + 1
            bb = bb + 1


            if (15 * (bb + 1)) >= 760:
                c.setFont("Verdana", 10)
                c.drawString(210, 800 - (15 * (bb + 1)), str(toplam))
                c.drawString(270, 800 - (15 * (bb + 1)), str(toplam1))
                c.drawString(350, 800 - (15 * (bb + 1)), str(toplam2))
                c.showPage()
                c.setFont("Verdana", 8)
                bb = 0
        c.setFont("Verdana", 10)
        self.ws1.write(aa+1, 3, toplam)
        self.ws1.write(aa+1, 4, toplam1)
        self.ws1.write(aa+1, 5, toplam2)
        c.drawString(270, 800 - (15 * (bb + 1)), str(toplam))
        c.drawString(350, 800 - (15 * (bb + 1)), str(toplam1))
        c.drawString(430, 800 - (15 * (bb + 1)), str(toplam2))

        #todo genel toplam yazılacak
        c.setFont("Courier", 60)
        # This next setting with make the text of our
        # watermark gray, nice touch for a watermark.
        c.setFillGray(0.3, 0.3)
        # Set up our watermark document. Our watermark
        # will be rotated 45 degrees from the direction
        # of our underlying document.
        c.saveState()
        c.translate(500, 100)
        c.rotate(45)
        c.drawCentredString(0, 0, "BISHOP NEN ©")
        c.drawCentredString(0, 300, "BISHOP NEN ©")
        c.drawCentredString(0, 600, "BISHOP NEN ©")
        c.restoreState()

        self.kontrol=0
        self.d.text("\n\n")

        item = "Genel Toplam "
        self.d.text(item.ljust(30) + " ")
        self.tableWidget.setItem(aa + 1, 0, QtGui.QTableWidgetItem(item))
        item = str(toplam1)
        self.d.text(item.rjust(10)+ " \n")
        self.tableWidget.setItem(aa + 1, 1, QtGui.QTableWidgetItem(item))

        item = "Kasa Kalan Nakit "
        self.d.text(item.ljust(30) + " ")
        self.tableWidget.setItem(aa + 2, 0, QtGui.QTableWidgetItem(item))
        item = str(toplam)
        self.d.text(item.rjust(10) + " \n")
        self.tableWidget.setItem(aa + 2, 1, QtGui.QTableWidgetItem(item))

        item = "Kredi Kart Toplam "
        self.d.text(item.ljust(30) + " ")
        self.tableWidget.setItem(aa + 3, 0, QtGui.QTableWidgetItem(item))
        item = str(toplam2)
        self.d.text(item.rjust(10)+ " \n")
        self.tableWidget.setItem(aa + 3, 1, QtGui.QTableWidgetItem(item))

        aa=aa+5
        self.d.text(u"\n\n\n Ödemeler \n")

        sql = """select
        aciklama, tutar
        from kasa where
        tutar < 0 and posid = 2000 and tarih
        between %s and %s """

        bul2 = myddb1.cur.execute(sql, (tar1, tar2))
        print bul2, tar1, tar2

        bul = myddb1.cur.fetchall()
        print bul
        i = bul2
        j = 5
        self.tableWidget.setRowCount(i + aa+1)

        bb = 0
        dep = 0
        toplam = 0.0
        toplam1 = 0.0
        toplam2 = 0.0000
        for row1 in bul:


            item = (row1[0])
      #      self.ws1.write(aa, 0, item)
            self.tableWidget.setItem(aa, 0, QtGui.QTableWidgetItem(item))
            c.drawString(150, 800 - (15 * (bb + 1)), item)
            self.d.text(item.ljust(30) + " ")
            item = str(row1[1])
            self.d.text(item.rjust(10) + " \n")
       #     self.ws1.write(aa, 3, float(row1[1]))
            c.drawRightString(310, 800 - (15 * (bb + 1)), item)
            toplam = Decimal(toplam) + (row1[1])

            toplam1 = Decimal(toplam1) + (row1[1])
            item = QtGui.QTableWidgetItem(item)
            item.setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignRight)
            self.tableWidget.setItem(aa, 1, item)

            aa=aa+1


        self.d.barcode(tar1, "CODE39", 80, 3)
        self.d.set(font='a', align='left', height=1, width=1)
        self.d.text(u"\n\n\n  İmza : \n")
        self.d.cut()
        c.save()
        self.wb.save(self.dest_filename)
Exemplo n.º 27
0
class Rapor(QtGui.QDialog , Ui_Dialog7):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        #self.myddb = Myddb()
        self.kontrol=0
        self.dt = datetime.now() - timedelta(hours=5)
        self.dt = QtCore.QDate.fromString(str(self.dt.date()), 'yyyy-MM-dd')

        self.tableWidget.setRowCount(0)
        self.dateEdit.setDate(self.dt)
        self.dateEdit_2.setDate(self.dt)
        self.pushButton.clicked.connect(self.sloturunmaliyet)
        self.pushButton_3.clicked.connect(self.sloturunmaliyetxls)
        self.pushButton_2.clicked.connect(self.sloturunmaliyetpdf)
        self.pushButton_4.clicked.connect(self.slotekstre)
        self.pushButton_5.clicked.connect(self.cariekstre)
        self.tableWidget.setColumnWidth(0, 50)
        self.tableWidget.setColumnWidth(1, 50)
        self.tableWidget.setColumnWidth(2, 450)
        self.tableWidget.setColumnWidth(3, 25)
        self.tableWidget.setColumnWidth(4, 25)
        getcontext().prec = 12

    @pyqtSlot()
    def sloturunmaliyet(self):

        myddb1 = Myddb()
        self.d = Dummy()
        self.kontrol=1

        self.d.text(chr(27))
        self.d.text(chr(116))
        self.d.text(chr(61))

        self.d.set(font='a', align='left', height=1, width=1)

        



        print "caribakiye listesi"
        self.tableWidget.clearContents()
        self.tableWidget.setColumnWidth(0, 50)
        self.tableWidget.setColumnWidth(1, 50)
        self.tableWidget.setColumnWidth(2, 400)
        self.tableWidget.setColumnWidth(3, 50)
        self.tableWidget.setColumnWidth(4, 50)

        deger1 = self.dateEdit.date().toPyDate()
        deger2 = self.dateEdit_2.date().toPyDate()
        tar1 = deger1.strftime('%d_%m_%Y')
        tar2 = deger2.strftime('%d_%m_%Y')
        self.d.text("  "+tar1+ "  " +tar2 +" Urun Rapor"+" \n")

        self.wb = xlwt.Workbook(encoding="utf-8")
        self.dest_filename = "EKSTRE" + tar1 + tar2 + ".xls"
        date_format = xlwt.XFStyle()
        date_format.num_format_str = u'#,##0.00₺'
        date_xf = xlwt.easyxf(num_format_str='DD-MM-YYYY')
        self.ws1 = self.wb.add_sheet("ekstre")
        self.style1 = xlwt.easyxf('pattern: pattern solid, fore_colour red;')

        c = canvas.Canvas("EKSTRE" + tar1 + tar2 + ".pdf")

        pdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf'))
        c.setFont("Verdana", 16)

        item = "            KOD       STOK ADI                                         BİRİM               GİRİŞ                ÇIKIŞ                 BAKİYE                      "
        c.drawString(10, 800, item)
        tar1 = deger1.strftime('%Y-%m-%d')
        tar2 = deger2.strftime('%Y-%m-%d')

        myddb1.cur.execute("drop table if exists test.table3 ")

        myddb1.cur.execute(""" CREATE TEMPORARY TABLE  test.table3 AS (SELECT ciro.departman,pluno,hamad,sum(adet),sum(tutar) FROM bishop.ciro  inner join test.hammadde on  pluno=hamkod and
 date(tarih) between %s and %s and hesap IS NULL group by ciro.departman,pluno order by ciro.departman asc)""",(tar1,tar2))

        sql = """select * from table3 ; """

        bul2 = myddb1.cur.execute(sql)
        print bul2, tar1, tar2
        bul = myddb1.cur.fetchall()
        i = bul2
        j = 5
        self.tableWidget.setRowCount(i + 2)
        aa = 0
        bb = 0
        dep=1
        toplam = 0.0
        toplam1 = 0.0
        toplam2 = 0.0000
        bolum = 0
        bolum1 = 0

        for row1 in bul:

            item = str(row1[0])
            if dep!=row1[0]:
                aa=aa+1
                self.d.text("\n")
                self.d.text("Toplam :      " + (str(bolum)).rjust(20) + (str(bolum1)).rjust(10) + "\n")
                self.d.text("\n")
                bolum = 0
                bolum1 = 0

            dep=row1[0]
            self.tableWidget.setItem(aa, 0, QtGui.QTableWidgetItem(item))
            c.drawString(5, 800 - (15 * (bb + 1)), item)
            self.ws1.write(aa,0,item)

            item = str(row1[1])
            c.drawString(50, 800 - (15 * (bb + 1)), item)
            self.ws1.write(aa, 1, item)
            self.d.text(item)
            self.d.text(" ")
            self.tableWidget.setItem(aa, 1, QtGui.QTableWidgetItem(item))
            item = row1[2]
            c.drawString(400, 800 - (15 * (bb + 1)), item)
            self.ws1.write(aa, 2, item)
            self.d.text(item.ljust(30))
            self.tableWidget.setItem(aa, 2, QtGui.QTableWidgetItem(item))

            item = str(row1[3])

            toplam = toplam + float(row1[3])
            bolum=bolum+ float(row1[3])
            self.tableWidget.setItem(aa, 3, QtGui.QTableWidgetItem(item))

            #c.drawRightString( 440, 800 - (15 * (bb + 1)), "{:10.2f}".format(row1[3]))
            self.ws1.write(aa, 3, float(row1[3]))
            self.d.text(item)
            self.d.text("  ")


            item = str(row1[4])

            toplam1 = toplam1 + float(row1[4])
            bolum1=bolum1+ float(row1[4])
            self.tableWidget.setItem(aa, 4, QtGui.QTableWidgetItem(item))

            c.drawRightString(510, 800 - (15 * (bb + 1)), "{:10.2f}".format(row1[4]))
            self.ws1.write(aa, 4, float(row1[4]))
            self.d.text(item.rjust(8)+"\n")


            aa = aa + 1
            bb = bb + 1

            if (15 * (bb + 1)) >= 760:
                c.setFont("Verdana", 11)
                c.drawRightString(330, 800 - (15 * (bb + 1)), str(toplam))
                c.drawRightString(405, 800 - (15 * (bb + 1)), str(toplam1))
                c.drawRightString(480, 800 - (15 * (bb + 1)), str(toplam2))
                c.showPage()
                c.setFont("Verdana", 16)
                bb = 0

        c.setFont("Verdana", 11)
        c.drawRightString(330, 800 - (15 * (bb + 1)), str(toplam))
        c.drawRightString(405, 800 - (15 * (bb + 1)), str(toplam1))
        c.drawRightString(480, 800 - (15 * (bb + 1)), str(toplam2))
        self.ws1.write(aa + 1, 3, toplam)
        self.ws1.write(aa + 1, 4, toplam1)
        self.ws1.write(aa + 1, 5, toplam2)

        c.setFont("Courier", 60)
        # This next setting with make the text of our
        # watermark gray, nice touch for a watermark.
        c.setFillGray(0.3, 0.3)
        # Set up our watermark document. Our watermark
        # will be rotated 45 degrees from the direction
        # of our underlying document.
        c.saveState()
        c.translate(500, 100)
        c.rotate(45)
        c.drawCentredString(0, 0, "BISHOP NEN ©")
        c.drawCentredString(0, 300, "BISHOP NEN ©")
        c.drawCentredString(0, 600, "BISHOP NEN ©")
        c.restoreState()

        c.save()
        self.wb.save(self.dest_filename)
        self.d.text("\n")
        self.d.text("Toplam :      " + (str(bolum)).rjust(20) + (str(bolum1)).rjust(10) + "\n")

        self.d.text("\n")
        self.d.text("Genel Toplam :      "+(str(toplam)).rjust(20)+(str(toplam1)).rjust(10)+"\n")

        self.d.cut()

    @pyqtSlot()
    def cariekstre(self):
        p = Network("192.168.2.222")
        p._raw(self.d.output)
        print "elma"
        p=None
        print p

 #       z._raw(self.d.output)

    @pyqtSlot(int,int)
    def slotekstre(self, item):
        if self.kontrol==0:
            print " kasa"
        myddb1 = Myddb()
        self.d = Dummy()
        self.d.text(chr(27))
        self.d.text(chr(116))
        self.d.text(chr(61))

        self.kontrol = 1
        self.d.set(font='a', align='left', height=2, width=1)

        print "ekstrerapor"
        self.tableWidget.clearContents()
        self.tableWidget.setColumnWidth(0, 150)
        self.tableWidget.setColumnWidth(1, 100)
        self.tableWidget.setColumnWidth(2, 75)
        self.tableWidget.setColumnWidth(3, 75)
        self.tableWidget.setColumnWidth(4, 75)
        self.tableWidget.setColumnWidth(5, 75)

        deger1 = self.dateEdit.date().toPyDate()
        deger2 = self.dateEdit_2.date().toPyDate()
        tar1 = deger1.strftime('%d_%m_%Y')
        tar2 = deger2.strftime('%d_%m_%Y')
        self.d.text("  " + tar1 + "  " + tar2 + " Kasa Raporu " + " \n\n")

        self.wb = xlwt.Workbook(encoding="utf-8")
        self.dest_filename = "EKSTRE" + tar1 + tar2 + ".xls"
        date_format = xlwt.XFStyle()
        date_format.num_format_str = u'#,##0.00₺'
        date_xf = xlwt.easyxf(num_format_str='DD/MM/YYYY')
        self.ws1 = self.wb.add_sheet("ekstre")
        self.style1 = xlwt.easyxf('pattern: pattern solid, fore_colour red;')

        c = canvas.Canvas("EKSTRE" + tar1 + tar2 + ".pdf")
        pdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf'))
        c.setFont("Verdana", 8)

        item = "         FİŞ NO       TARİH                AÇIKLAMA                             BORÇ                  ALACAK                    BAKİYE                      "
        c.drawString(10, 810, item)
        tar1 = deger1.strftime('%Y-%m-%d')
        tar2 = deger2.strftime('%Y-%m-%d')

        sql = """select kasano,sum(tutar) from kasa where date(tarih) between %s and %s  group by kasano; """

        bul2 = myddb1.cur.execute(sql, (tar1, tar2))
        print bul2, tar1, tar2

        bul = myddb1.cur.fetchall()
        i = bul2
        j = 5
        self.tableWidget.setRowCount(i+5)
        aa = 0
        bb = 0
        dep=0
        toplam = 0.0
        toplam1 = 0.0
        toplam2 = 0.0000
        for row1 in bul:


            if row1[0]==100:
                item = str(row1[0])+" Nakit "
                self.ws1.write(aa, 0, item)
                self.tableWidget.setItem(aa, 0, QtGui.QTableWidgetItem(item))
                c.drawString(150, 800 - (15 * (bb + 1)), item)
                self.d.text(item.ljust(30) + " ")
                item = str(row1[1])
                self.d.text(item.rjust(10) + " \n")
                self.ws1.write(aa, 3, float(row1[1]))
                c.drawRightString(310, 800 - (15 * (bb + 1)), item)
                toplam = Decimal(toplam) + (row1[1])

                toplam1 = Decimal(toplam1) + (row1[1])
                item=QtGui.QTableWidgetItem(item)
                item.setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignRight)
                self.tableWidget.setItem(aa, 1, item)

                item= ""
                c.drawRightString(390, 800 - (15 * (bb + 1)), item)
                self.tableWidget.setItem(aa, 2, QtGui.QTableWidgetItem(item))


            if row1[0]==101:
                item = str(row1[0]) + " Indirim "
                self.ws1.write(aa, 0, item)
                self.tableWidget.setItem(aa, 0, QtGui.QTableWidgetItem(item))
                c.drawString(150, 800 - (15 * (bb + 1)), item)
                self.d.text(item.ljust(30) + " ")

                item = str(row1[1])
                self.d.text(item.rjust(10) + " \n")
                self.ws1.write(aa, 3, float(row1[1]))
                c.drawRightString(310, 800 - (15 * (bb + 1)), item)

                self.tableWidget.setItem(aa, 1, QtGui.QTableWidgetItem(item))
                item = ""
                c.drawRightString(390, 800 - (15 * (bb + 1)), item)
                self.tableWidget.setItem(aa, 2, QtGui.QTableWidgetItem(item))

            if row1[0]==102:
                item = str(row1[0])+" Servis "
                self.ws1.write(aa, 0, item)
                self.tableWidget.setItem(aa, 0, QtGui.QTableWidgetItem(item))
                c.drawString(150, 800 - (15 * (bb + 1)), item)
                self.d.text(item.ljust(30) + " ")

                item = str(row1[1])
                self.d.text(item.rjust(10)+ " \n")
                self.ws1.write(aa, 3, float(row1[1]))
                c.drawRightString(310, 800 - (15 * (bb + 1)), item)
                toplam = Decimal(toplam) - (row1[1])
                self.tableWidget.setItem(aa, 1, QtGui.QTableWidgetItem(item))
                item= ""
                c.drawRightString(390, 800 - (15 * (bb + 1)), item)
                self.tableWidget.setItem(aa, 2, QtGui.QTableWidgetItem(item))

            if row1[0]==105:
                item = str(row1[0])+" Denizbank "
                self.ws1.write(aa, 0, item)
                self.tableWidget.setItem(aa, 0, QtGui.QTableWidgetItem(item))
                c.drawString(150, 800 - (15 * (bb + 1)), item)
                self.d.text(item.ljust(30) + " ")

                item = str(row1[1])
                self.ws1.write(aa, 3, float(row1[1]))
                c.drawRightString(310, 800 - (15 * (bb + 1)), item)
                toplam2=Decimal(toplam2)+(row1[1])
                toplam1 = Decimal(toplam1) + (row1[1])
                self.tableWidget.setItem(aa, 1, QtGui.QTableWidgetItem(item))
                self.d.text(item.rjust(10)+ " \n")
                self.tableWidget.item(aa, 1).setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignRight)

                item= ""
                c.drawRightString(390, 800 - (15 * (bb + 1)), item)
                self.tableWidget.setItem(aa, 2, QtGui.QTableWidgetItem(item))

            if row1[0]==106:
                item = str(row1[0])+" Yapi Kredi "
                self.ws1.write(aa, 0, item)
                self.d.text(item.ljust(30) + " ")
                self.tableWidget.setItem(aa, 0, QtGui.QTableWidgetItem(item))
                c.drawString(150, 800 - (15 * (bb + 1)), item)

                item = str(row1[1])
                self.d.text(item.rjust(10)+ " \n")
                self.ws1.write(aa, 3, float(row1[1]))
                c.drawRightString(310, 800 - (15 * (bb + 1)), item)
                toplam2=Decimal(toplam2)+(row1[1])
                toplam1 = Decimal(toplam1) + (row1[1])
                self.tableWidget.setItem(aa, 1, QtGui.QTableWidgetItem(item))
                item= ""
                c.drawRightString(390, 800 - (15 * (bb + 1)), item)
                self.tableWidget.setItem(aa, 2, QtGui.QTableWidgetItem(item))

            if row1[0]==111:
                item = str(row1[0])+" Harcamalar "
                self.ws1.write(aa, 0, item)
                self.d.text(item.ljust(30) + " ")
                self.tableWidget.setItem(aa, 0, QtGui.QTableWidgetItem(item))
                c.drawString(150, 800 - (15 * (bb + 1)), item)

                item = str(row1[1])
                self.d.text(item.rjust(10)+ " \n")
                self.ws1.write(aa, 3, float(row1[1]))
                c.drawRightString(310, 800 - (15 * (bb + 1)), item)
                toplam = Decimal(toplam) + (row1[1])
                self.tableWidget.setItem(aa, 1, QtGui.QTableWidgetItem(item))
                item= ""
                c.drawRightString(390, 800 - (15 * (bb + 1)), item)
                self.tableWidget.setItem(aa, 2, QtGui.QTableWidgetItem(item))





            aa = aa + 1
            bb = bb + 1


            if (15 * (bb + 1)) >= 760:
                c.setFont("Verdana", 10)
                c.drawString(210, 800 - (15 * (bb + 1)), str(toplam))
                c.drawString(270, 800 - (15 * (bb + 1)), str(toplam1))
                c.drawString(350, 800 - (15 * (bb + 1)), str(toplam2))
                c.showPage()
                c.setFont("Verdana", 8)
                bb = 0
        c.setFont("Verdana", 10)
        self.ws1.write(aa+1, 3, toplam)
        self.ws1.write(aa+1, 4, toplam1)
        self.ws1.write(aa+1, 5, toplam2)
        c.drawString(270, 800 - (15 * (bb + 1)), str(toplam))
        c.drawString(350, 800 - (15 * (bb + 1)), str(toplam1))
        c.drawString(430, 800 - (15 * (bb + 1)), str(toplam2))

        #todo genel toplam yazılacak
        c.setFont("Courier", 60)
        # This next setting with make the text of our
        # watermark gray, nice touch for a watermark.
        c.setFillGray(0.3, 0.3)
        # Set up our watermark document. Our watermark
        # will be rotated 45 degrees from the direction
        # of our underlying document.
        c.saveState()
        c.translate(500, 100)
        c.rotate(45)
        c.drawCentredString(0, 0, "BISHOP NEN ©")
        c.drawCentredString(0, 300, "BISHOP NEN ©")
        c.drawCentredString(0, 600, "BISHOP NEN ©")
        c.restoreState()

        self.kontrol=0
        self.d.text("\n\n")

        item = "Genel Toplam "
        self.d.text(item.ljust(30) + " ")
        self.tableWidget.setItem(aa + 1, 0, QtGui.QTableWidgetItem(item))
        item = str(toplam1)
        self.d.text(item.rjust(10)+ " \n")
        self.tableWidget.setItem(aa + 1, 1, QtGui.QTableWidgetItem(item))

        item = "Kasa Kalan Nakit "
        self.d.text(item.ljust(30) + " ")
        self.tableWidget.setItem(aa + 2, 0, QtGui.QTableWidgetItem(item))
        item = str(toplam)
        self.d.text(item.rjust(10) + " \n")
        self.tableWidget.setItem(aa + 2, 1, QtGui.QTableWidgetItem(item))

        item = "Kredi Kart Toplam "
        self.d.text(item.ljust(30) + " ")
        self.tableWidget.setItem(aa + 3, 0, QtGui.QTableWidgetItem(item))
        item = str(toplam2)
        self.d.text(item.rjust(10)+ " \n")
        self.tableWidget.setItem(aa + 3, 1, QtGui.QTableWidgetItem(item))

        aa=aa+5
        self.d.text(u"\n\n\n Ödemeler \n")

        sql = """select
        aciklama, tutar
        from kasa where
        tutar < 0 and posid = 2000 and tarih
        between %s and %s """

        bul2 = myddb1.cur.execute(sql, (tar1, tar2))
        print bul2, tar1, tar2

        bul = myddb1.cur.fetchall()
        print bul
        i = bul2
        j = 5
        self.tableWidget.setRowCount(i + aa+1)

        bb = 0
        dep = 0
        toplam = 0.0
        toplam1 = 0.0
        toplam2 = 0.0000
        for row1 in bul:


            item = (row1[0])
      #      self.ws1.write(aa, 0, item)
            self.tableWidget.setItem(aa, 0, QtGui.QTableWidgetItem(item))
            c.drawString(150, 800 - (15 * (bb + 1)), item)
            self.d.text(item.ljust(30) + " ")
            item = str(row1[1])
            self.d.text(item.rjust(10) + " \n")
       #     self.ws1.write(aa, 3, float(row1[1]))
            c.drawRightString(310, 800 - (15 * (bb + 1)), item)
            toplam = Decimal(toplam) + (row1[1])

            toplam1 = Decimal(toplam1) + (row1[1])
            item = QtGui.QTableWidgetItem(item)
            item.setTextAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignRight)
            self.tableWidget.setItem(aa, 1, item)

            aa=aa+1


        self.d.barcode(tar1, "CODE39", 80, 3)
        self.d.set(font='a', align='left', height=1, width=1)
        self.d.text(u"\n\n\n  İmza : \n")
        self.d.cut()
        c.save()
        self.wb.save(self.dest_filename)

    @pyqtSlot()
    def sloturunmaliyetpdf(self):
        deger1 = self.dateEdit.date().toPyDate()
        deger2 = self.dateEdit_2.date().toPyDate()
        tar1 = deger1.strftime('%d%m%Y')
        tar2 = deger2.strftime('%d%m%Y')

        if sys.platform == "win32":
            os.startfile("EKSTRE" + tar1 + tar2 + ".pdf")
        else:
            opener = "open" if sys.platform == "darwin" else "xdg-open"
            subprocess.call([opener, "EKSTRE" + tar1 + tar2 + ".pdf"])

    def sloturunmaliyetxls(self):
        deger1 = self.dateEdit.date().toPyDate()
        deger2 = self.dateEdit_2.date().toPyDate()
        tar1 = deger1.strftime('%d%m%Y')
        tar2 = deger2.strftime('%d%m%Y')

        if sys.platform == "win32":
            os.startfile("EKSTRE" + tar1 + tar2 + ".xls")
        else:
            opener = "open" if sys.platform == "darwin" else "xdg-open"
            subprocess.call([opener, "EKSTRE" + tar1 + tar2 + ".xls"])
Exemplo n.º 28
0
    def sloturunmaliyet(self):

        myddb1 = Myddb()
        self.d = Dummy()
        self.kontrol=1

        self.d.text(chr(27))
        self.d.text(chr(116))
        self.d.text(chr(61))

        self.d.set(font='a', align='left', height=1, width=1)

        



        print "caribakiye listesi"
        self.tableWidget.clearContents()
        self.tableWidget.setColumnWidth(0, 50)
        self.tableWidget.setColumnWidth(1, 50)
        self.tableWidget.setColumnWidth(2, 400)
        self.tableWidget.setColumnWidth(3, 50)
        self.tableWidget.setColumnWidth(4, 50)

        deger1 = self.dateEdit.date().toPyDate()
        deger2 = self.dateEdit_2.date().toPyDate()
        tar1 = deger1.strftime('%d_%m_%Y')
        tar2 = deger2.strftime('%d_%m_%Y')
        self.d.text("  "+tar1+ "  " +tar2 +" Urun Rapor"+" \n")

        self.wb = xlwt.Workbook(encoding="utf-8")
        self.dest_filename = "EKSTRE" + tar1 + tar2 + ".xls"
        date_format = xlwt.XFStyle()
        date_format.num_format_str = u'#,##0.00₺'
        date_xf = xlwt.easyxf(num_format_str='DD-MM-YYYY')
        self.ws1 = self.wb.add_sheet("ekstre")
        self.style1 = xlwt.easyxf('pattern: pattern solid, fore_colour red;')

        c = canvas.Canvas("EKSTRE" + tar1 + tar2 + ".pdf")

        pdfmetrics.registerFont(TTFont('Verdana', 'Verdana.ttf'))
        c.setFont("Verdana", 16)

        item = "            KOD       STOK ADI                                         BİRİM               GİRİŞ                ÇIKIŞ                 BAKİYE                      "
        c.drawString(10, 800, item)
        tar1 = deger1.strftime('%Y-%m-%d')
        tar2 = deger2.strftime('%Y-%m-%d')

        myddb1.cur.execute("drop table if exists test.table3 ")

        myddb1.cur.execute(""" CREATE TEMPORARY TABLE  test.table3 AS (SELECT ciro.departman,pluno,hamad,sum(adet),sum(tutar) FROM bishop.ciro  inner join test.hammadde on  pluno=hamkod and
 date(tarih) between %s and %s and hesap IS NULL group by ciro.departman,pluno order by ciro.departman asc)""",(tar1,tar2))

        sql = """select * from table3 ; """

        bul2 = myddb1.cur.execute(sql)
        print bul2, tar1, tar2
        bul = myddb1.cur.fetchall()
        i = bul2
        j = 5
        self.tableWidget.setRowCount(i + 2)
        aa = 0
        bb = 0
        dep=1
        toplam = 0.0
        toplam1 = 0.0
        toplam2 = 0.0000
        bolum = 0
        bolum1 = 0

        for row1 in bul:

            item = str(row1[0])
            if dep!=row1[0]:
                aa=aa+1
                self.d.text("\n")
                self.d.text("Toplam :      " + (str(bolum)).rjust(20) + (str(bolum1)).rjust(10) + "\n")
                self.d.text("\n")
                bolum = 0
                bolum1 = 0

            dep=row1[0]
            self.tableWidget.setItem(aa, 0, QtGui.QTableWidgetItem(item))
            c.drawString(5, 800 - (15 * (bb + 1)), item)
            self.ws1.write(aa,0,item)

            item = str(row1[1])
            c.drawString(50, 800 - (15 * (bb + 1)), item)
            self.ws1.write(aa, 1, item)
            self.d.text(item)
            self.d.text(" ")
            self.tableWidget.setItem(aa, 1, QtGui.QTableWidgetItem(item))
            item = row1[2]
            c.drawString(400, 800 - (15 * (bb + 1)), item)
            self.ws1.write(aa, 2, item)
            self.d.text(item.ljust(30))
            self.tableWidget.setItem(aa, 2, QtGui.QTableWidgetItem(item))

            item = str(row1[3])

            toplam = toplam + float(row1[3])
            bolum=bolum+ float(row1[3])
            self.tableWidget.setItem(aa, 3, QtGui.QTableWidgetItem(item))

            #c.drawRightString( 440, 800 - (15 * (bb + 1)), "{:10.2f}".format(row1[3]))
            self.ws1.write(aa, 3, float(row1[3]))
            self.d.text(item)
            self.d.text("  ")


            item = str(row1[4])

            toplam1 = toplam1 + float(row1[4])
            bolum1=bolum1+ float(row1[4])
            self.tableWidget.setItem(aa, 4, QtGui.QTableWidgetItem(item))

            c.drawRightString(510, 800 - (15 * (bb + 1)), "{:10.2f}".format(row1[4]))
            self.ws1.write(aa, 4, float(row1[4]))
            self.d.text(item.rjust(8)+"\n")


            aa = aa + 1
            bb = bb + 1

            if (15 * (bb + 1)) >= 760:
                c.setFont("Verdana", 11)
                c.drawRightString(330, 800 - (15 * (bb + 1)), str(toplam))
                c.drawRightString(405, 800 - (15 * (bb + 1)), str(toplam1))
                c.drawRightString(480, 800 - (15 * (bb + 1)), str(toplam2))
                c.showPage()
                c.setFont("Verdana", 16)
                bb = 0

        c.setFont("Verdana", 11)
        c.drawRightString(330, 800 - (15 * (bb + 1)), str(toplam))
        c.drawRightString(405, 800 - (15 * (bb + 1)), str(toplam1))
        c.drawRightString(480, 800 - (15 * (bb + 1)), str(toplam2))
        self.ws1.write(aa + 1, 3, toplam)
        self.ws1.write(aa + 1, 4, toplam1)
        self.ws1.write(aa + 1, 5, toplam2)

        c.setFont("Courier", 60)
        # This next setting with make the text of our
        # watermark gray, nice touch for a watermark.
        c.setFillGray(0.3, 0.3)
        # Set up our watermark document. Our watermark
        # will be rotated 45 degrees from the direction
        # of our underlying document.
        c.saveState()
        c.translate(500, 100)
        c.rotate(45)
        c.drawCentredString(0, 0, "BISHOP NEN ©")
        c.drawCentredString(0, 300, "BISHOP NEN ©")
        c.drawCentredString(0, 600, "BISHOP NEN ©")
        c.restoreState()

        c.save()
        self.wb.save(self.dest_filename)
        self.d.text("\n")
        self.d.text("Toplam :      " + (str(bolum)).rjust(20) + (str(bolum1)).rjust(10) + "\n")

        self.d.text("\n")
        self.d.text("Genel Toplam :      "+(str(toplam)).rjust(20)+(str(toplam1)).rjust(10)+"\n")

        self.d.cut()
Exemplo n.º 29
0
class DummyPrinter(object):
    def __init__(self):
        pass

    # TODO: find a way to clear out this set

    def print_ticket(self, order):
        self.d = Dummy()
        self.d.line_spacing(120)
        self.d.ln(1)

        self.d.set(align="center",
                   bold=True,
                   underline=2,
                   double_height=False,
                   double_width=False,
                   custom_size=True,
                   smooth=True,
                   width=2,
                   height=2,
                   invert=False,
                   density=8,
                   font='a')
        self.d.block_text(str(order.order_number) + ' ' + order.name + '\n',
                          font='a')
        self.d.ln(1)

        self.d.set(align="center",
                   bold=False,
                   underline=0,
                   double_height=False,
                   double_width=False,
                   custom_size=True,
                   smooth=True,
                   width=2,
                   height=2,
                   invert=False,
                   density=8,
                   font='a')
        self.d.block_text(order.order_type + '\n', columns=20, font='a')
        self.d.ln(1)

        self.d.text(order.formatted_number + '\n')
        self.d.text(order.date + '\n')
        self.d.text(order.time + '\n')
        self.d.text(' \n')

        self.d.set(align="left",
                   bold=True,
                   underline=0,
                   double_height=False,
                   double_width=False,
                   custom_size=True,
                   smooth=True,
                   width=2,
                   height=2,
                   invert=False,
                   density=8,
                   font='b')
        self.d.text('PICKUP TIME\n')

        self.d.set(align="left",
                   bold=False,
                   underline=0,
                   double_height=False,
                   double_width=False,
                   custom_size=True,
                   smooth=True,
                   width=2,
                   height=2,
                   invert=False,
                   density=8,
                   font='a')
        self.d.block_text(order.pickup_time + '\n', columns=20, font='a')

        self.d.ln(2)

        self.d.set(align="left",
                   bold=True,
                   underline=0,
                   double_height=False,
                   double_width=False,
                   custom_size=True,
                   smooth=True,
                   width=2,
                   height=2,
                   invert=False,
                   density=8,
                   font='b')
        self.d.text('ORDER\n')

        self.d.set(align="left",
                   bold=False,
                   underline=0,
                   double_height=False,
                   double_width=False,
                   custom_size=True,
                   smooth=True,
                   width=2,
                   height=2,
                   invert=False,
                   density=8,
                   font='a')
        self.d.block_text(order.order + '\n', columns=20, font='a')

        self.d.ln(2)

        if order.notes != '':
            self.d.set(align="left",
                       bold=True,
                       underline=0,
                       double_height=False,
                       double_width=False,
                       custom_size=True,
                       smooth=True,
                       width=2,
                       height=2,
                       invert=False,
                       density=8,
                       font='b')
            self.d.text('NOTES\n')

            self.d.set(align="left",
                       bold=False,
                       underline=0,
                       double_height=False,
                       double_width=False,
                       custom_size=True,
                       smooth=True,
                       width=2,
                       height=2,
                       invert=False,
                       density=8,
                       font='a')
            self.d.block_text(order.notes + '\n', columns=20, font='a')

        self.d.cut()

    def print_error_message(self, error_message):
        pass
def get_printer():
    return Dummy(magic_encode_args={"disabled": True, "encoding": "CP437"})
Exemplo n.º 31
0
def print_message(message, header):
    """
    Prints a message through the POS printer with set formatting.
    Does __not__ take note of the current enable setting for the printer.

    TODO: Handle NoneType in any message field

    :param message: instance of class HoppieMessage
    :param header: string, printout header
    :return: nil
    """

    bold_emphasis = b"\x1b\x21\x08"  # Sets text to bold
    second_typeface_emphasis = b"\x1b\x21\x01"  # Selects font B (different code to actual font size stuff)
    reset_emphasis = b"\x1b\x21\x00"  # Reset emphasis
    font_size_2x = b"\x1d\x21\x10"  # Change text size to 2x
    font_reset = b"\x1d\x21\x00"  # Reset text size

    dpos = Dummy()

    # print header
    dpos._raw(reset_emphasis)
    dpos._raw(font_size_2x)
    dpos.text(header + "\n")
    dpos._raw(font_reset)

    # print associated time
    dpos._raw(second_typeface_emphasis)
    dpos.text(f"Received {datetime.datetime.utcfromtimestamp(message.time).strftime('%d-%H%Mz')}")
    dpos.text("\n")
    dpos._raw(reset_emphasis)

    # print message type
    dpos._raw(bold_emphasis)
    dpos.text("Type: ")
    dpos._raw(reset_emphasis)
    dpos.text("{}\n".format(message.mode))

    # print sender
    dpos._raw(bold_emphasis)
    dpos.text("From: ")
    dpos._raw(reset_emphasis)
    dpos.text("{}\n".format(message.sender))

    # print message
    dpos._raw(bold_emphasis)
    dpos.text("Message: ")
    dpos._raw(reset_emphasis)
    dpos.text("{}\n\n\n".format(message.message))

    pos.print(dpos.output)

    helper.add_event((lambda: True), (lambda: ui.statusbar.showMessage("Commands sent to printer")))
 def __init__(self):
     printer = Dummy()
     self.print_self(printer)
     self.raw_print = printer.output
Exemplo n.º 33
0
def test_line_spacing_rest():
    printer = Dummy()
    printer.line_spacing()
    assert printer.output == b'\x1b2'
Exemplo n.º 34
0
    def perform_create(self, serializer):
        lateness = serializer.save()
        printing = self.request.query_params.get('print', None)

        lateness_settings = get_settings()

        lateness_count = self.get_queryset().filter(
            student=lateness.student,
            justified=False,
        ).count()

        if lateness_settings.printer and printing:
            try:
                printer = Network(lateness_settings.printer) if not settings.DEBUG else Dummy()
                printer.charcode('USA')
                printer.set(align='CENTER', text_type='B')
                printer.text('RETARD\n')
                printer.set(align='LEFT')
                absence_dt = lateness.datetime_creation.astimezone(timezone.get_default_timezone())

                count_or_justified = "Retard justifié" if lateness.justified else "Nombre de retards: "
                if not lateness.justified:
                    count_or_justified += "%i" % lateness_count

                printer.text('\n%s %s\n%s\n%s\n%s\nBonne journée !' % (
                    unidecode(lateness.student.last_name),
                    unidecode(lateness.student.first_name),
                    lateness.student.classe.compact_str,
                    absence_dt.strftime("%H:%M - %d/%m/%Y"),
                    count_or_justified
                ))
                if settings.DEBUG:
                    print(printer.output)
                printer.cut()
                printer.close()
            except OSError:
                pass

        for trigger in SanctionTriggerModel.objects.filter(
            teaching=lateness.student.teaching,
            year__year=lateness.student.classe.year
        ):
            count_first = trigger.lateness_count_trigger_first
            count_trigger = trigger.lateness_count_trigger
            if lateness_count < count_first or (
                lateness_count > count_first and (lateness_count - count_first) % count_trigger != 0
            ):
                continue

            lateness.has_sanction = True
            if trigger.only_warn:
                lateness.save()
                continue
            from dossier_eleve.models import CasEleve, SanctionDecisionDisciplinaire

            sanction = SanctionDecisionDisciplinaire.objects.get(id=trigger.sanction_id)
            today = datetime.datetime.today()
            day_shift = 6 + trigger.next_week_day
            day = today + datetime.timedelta(days=(day_shift - today.isoweekday()) % (6 + trigger.delay) + 1)
            day.replace(hour=trigger.sanction_time.hour, minute=trigger.sanction_time.minute)
            cas = CasEleve.objects.create(
                matricule=lateness.student, name=lateness.student.display,
                demandeur=self.request.user.get_full_name(),
                sanction_decision=sanction,
                explication_commentaire="Sanction pour cause de retard.",
                sanction_faite=False,
                datetime_sanction=day,
                created_by=self.request.user
            )
            cas.visible_by_groups.set(Group.objects.all())
            lateness.sanction_id = cas.id
            lateness.save()

        if lateness_settings.notify_responsible:
            responsibles = get_resp_emails(lateness.student)
            context = {"lateness": lateness, "lateness_count": lateness_count}
            send_email(
                responsibles,
                "[Retard]%s  %s %s" % (
                    "[Sanction]" if lateness.has_sanction else "",
                    lateness.student.fullname, lateness.student.classe.compact_str
                ),
                "lateness/lateness_email.html",
                context=context
            )
Exemplo n.º 35
0
def test_line_spacing_code_gen():
    printer = Dummy()
    printer.line_spacing(10)
    assert printer.output == b'\x1b3\n'
Exemplo n.º 36
0
class Receipt:
    def __init__(self, uid, pid):
        self.p = Dummy()

        self.qanswered = 0
        self.id = uid
        self.pid = pid

    def startRecording(self):
        self.start_time = time.time()
        self.sequence = []
        self.chord = []

    def recordNote(self, note):
        curr_time = time.time()
        if curr_time < self.start_time + 0.125:
            self.chord.append(note)
        else:
            self.sequence.append(self.chord)
            self.chord = [note]
            num_rest = (curr_time - (self.start_time + 0.125)) / 0.125
            for r in xrange(int(num_rest)):
                self.sequence.append(None)
            self.start_time = self.start_time + (num_rest + 1) * 0.125

    def endRecording(self):
        self.sequence.append(self.chord)
        self.addSequence(self.sequence, True)

    def startFreeRecording(self):
        self.sequence = []

    def recordFreeNote(self, note):
        self.sequence.append((note, time.time()))

    def endFreeRecording(self):
        self.addFreeSequence(self.sequence)

    def saveToText(self, fn):
        f = File(fn)
        f._raw(self.p.output)
        f.cut()

    def addFreeSequence(self, sequence):
        seq_len = len(sequence)
        if seq_len != 0:
            self.createFreeSequence(sequence[0][1] - 0.5,
                                    sequence[seq_len - 1][1] + 0.5, sequence)
            self.p.image("line.ppm")

    def addSequence(self, notes_list, half=False):
        for n in notes_list:
            if n is None:
                self.addRest(half)
            else:
                self.addChord(n, half)

    def addChord(self, notes, half=False):
        if half:
            self.createChordHalf(notes)
        else:
            self.createChord(notes)
        self.p.image("line.ppm")

    def addRest(self, half=False):
        if half:
            self.p.image("empty_half.ppm")
        else:
            self.p.image("empty.ppm")

    def createFreeSequence(self, start_time, end_time, sequence):
        width = col_end + 1
        height = int(row_height * (end_time - start_time) / 0.25)

        img = Image.new('RGB', (width, height), "white")
        pixels = img.load()

        for n, t in sequence:
            x_cent = self.getXForNote(n)
            y_cent = int(row_height * (t - start_time) / 0.25)
            for i in xrange(x_cent - 5, x_cent + 5):
                for j in xrange(y_cent - 5, y_cent + 5):
                    pixels[i, j] = (0, 0, 0)

        for j in xrange(height):
            pixels[col_end, j] = (0, 0, 0)

        img.save('line.ppm')

    def createChord(self, notes):
        width = col_end + 1
        height = row_height

        img = Image.new('RGB', (width, height), "white")
        pixels = img.load()

        for n in notes:
            i_cent = self.getXForNote(n)
            for i in xrange(i_cent - 5, i_cent + 5):
                for j in xrange(row_height / 2 - 5, row_height / 2 + 5):
                    pixels[i, j] = (0, 0, 0)

        for j in xrange(height):
            pixels[col_end, j] = (0, 0, 0)

        img.save('line.ppm')

    def createChordHalf(self, notes):
        width = col_end + 1
        height = row_height_half

        img = Image.new('RGB', (width, height), "white")
        pixels = img.load()

        for n in notes:
            i_cent = self.getXForNote(n)
            for i in xrange(i_cent - 5, i_cent + 5):
                for j in xrange(row_height_half / 2 - 5,
                                row_height_half / 2 + 5):
                    pixels[i, j] = (0, 0, 0)

        for j in xrange(height):
            pixels[col_end, j] = (0, 0, 0)

        img.save('line.ppm')

    def resetRest(self):
        img = Image.new('RGB', (col_end + 1, row_height), "white")
        pixels = img.load()

        for j in xrange(row_height):
            pixels[col_end, j] = (0, 0, 0)

        img.save('empty.ppm')

        img = Image.new('RGB', (col_end + 1, row_height_half), "white")
        pixels = img.load()

        for j in xrange(row_height_half):
            pixels[col_end, j] = (0, 0, 0)

        img.save('empty_half.ppm')

    def getXForNote(self, note):
        return col_lead + col_width * note
def test_printer_dummy_clear():
    printer = Dummy()
    printer.text("Hello")
    printer.clear()
    assert printer.output == b""
Exemplo n.º 38
0
def test_function_text_dies_ist_ein_test_lf():
    """test the text printing function with simple string and compare output"""
    instance = Dummy()
    instance.text('Dies ist ein Test.\n')
    assert instance.output == b'Dies ist ein Test.\n'