50 lines
1.8 KiB
Python
50 lines
1.8 KiB
Python
import base64
|
|
from io import BytesIO
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from modules.fulfillment_base.barcodes_pdf_gen import BarcodePdfGenerator, BarcodeData
|
|
from modules.fulfillment_base.barcodes_pdf_gen.types import PdfBarcodeImageGenData
|
|
from modules.fulfillment_base.models import Product
|
|
from modules.fulfillment_base.repositories import ProductRepository
|
|
from modules.fulfillment_base.schemas.product import GetProductBarcodePdfRequest
|
|
|
|
|
|
class BarcodePrinterService:
|
|
session: AsyncSession
|
|
|
|
def __init__(self, session: AsyncSession):
|
|
self.session = session
|
|
|
|
async def generate_pdf(
|
|
self, request: GetProductBarcodePdfRequest
|
|
) -> tuple[str, BytesIO]:
|
|
product: Product = await ProductRepository(self.session).get_by_id(
|
|
request.product_id
|
|
)
|
|
if product.barcode_image:
|
|
barcode_data: PdfBarcodeImageGenData = {
|
|
"barcode_image_url": product.barcode_image.image_url,
|
|
"num_duplicates": request.quantity,
|
|
}
|
|
else:
|
|
barcode_data: BarcodeData = {
|
|
"barcode": request.barcode,
|
|
"template": product.barcode_template,
|
|
"product": product,
|
|
"num_duplicates": request.quantity,
|
|
}
|
|
|
|
filename = f"{product.id}_barcode.pdf"
|
|
|
|
size = product.barcode_template.size
|
|
generator = BarcodePdfGenerator(size.width, size.height)
|
|
return filename, await generator.generate([barcode_data])
|
|
|
|
async def generate_base64(
|
|
self, request: GetProductBarcodePdfRequest
|
|
) -> tuple[str, str]:
|
|
filename, pdf_buffer = await self.generate_pdf(request)
|
|
base64_string = base64.b64encode(pdf_buffer.read()).decode("utf-8")
|
|
return filename, base64_string
|