def handle(self, pi, id): from applications.good.service import GoodService inventory = InventoryService.get_by_id(id) su = sum(map( lambda it: GoodService.get_price( it.good_id).price_retail * it.count_after, inventory.items)) pi.set_cells(0, 0, [('number', 2)]) pi.set_cells(0, 2, ['a', 'date', 'c', 'c', 'c', 'sum']) pi.set_cells(0, 3, ['a', 'pointsale']) pi.set_cells(0, 6, [('name', 5), 'price', 'a', 'count', 'b', 'c', 'd']) pi.write(0, 0, 0, [{'number': inventory.number}]) pi.write(0, 2, 1, [{'date': inventory.datetimenew.strftime( "%d.%m.%Y - %H:%M:%S"), 'sum': su}]) pi.write(0, 3, 0, [{'pointsale': inventory.location.name}]) items = [ {'name': it.good.full_name, 'count': it.count_after or "", 'price': GoodService.get_price(it.good_id).price_retail, 'a': '', 'b': '', 'c': '', 'd': ''} for it in inventory.items] pi.write(0, 6, 2, items)
def sync_from_json(cls, obj, json): """ Сохранение позиций инвентаризации. """ from applications.good.service import GoodService if obj.status not in [VALIDATED, DRAFT]: debug(u"Удаление связанных записей в инвентаризации (%s)" % obj.id) obj.items.delete() debug(u"Старт: Заполнение новых записей в инвентаризацию (%s)" % obj.id) for item in json: if COUNT_AFTER_ATTR not in item: good = GoodService.get_good(item[GOOD_ATTR][GOOD_ID_ATTR]) raise InventoryService.InventoryServiceException( u"Товар %s без количества после инвентаризации, не " u"может быть сохранен в (%s)." % ( good.full_name, obj)) in_item = cls.create_item( obj.id, item[GOOD_ATTR][GOOD_ID_ATTR], item[COUNT_BEFORE_ATTR] if COUNT_BEFORE_ATTR in item and item[COUNT_BEFORE_ATTR] else 0, item[COUNT_AFTER_ATTR]) db.session.add(in_item) debug(u"Конец: Заполнение новых записей в инвентаризацию (%s)" % obj.id) else: debug(u"В статусе %s и %s позиции в инвентаризацию (%s) не " u"сохраняются." % (VALIDATED, DRAFT, obj.id))
def upgrade_items(cls, waybill, items, path_target=None, path=None): from applications.price.service import PriceService from applications.good.service import GoodService waybill.items.delete() db.session.add(waybill) for it in items: good = GoodService.get_good(it.good_id) if waybill.type == RETAIL: if not good.price_id or not PriceService.get_price( good.price_id).price_retail: raise WayBillServiceException( u"Товар без розничной цены. %s" % good.full_name) else: if not good.price_id or not PriceService.get_price( good.price_id).price_gross: raise WayBillServiceException( u"Товар без оптовой цены. %s" % good.full_name) if it.count and not WayBillService.check_count( invoice_id=waybill.invoice_id, waybill_id=waybill.id, good_id=it.good_id, count=int(it.count)): raise WayBillServiceException( u"Недостаточно товара %s" % good.full_name) retail_item = WayBillItems( good_id=good.id, waybill=waybill, count=it.count if it.count else None) db.session.add(retail_item)
def update_fact_count_custom(cls, acceptance, items): debug(u"Обновление фактического кол-ва по новой `прихода` id = '%s' " u"начато." % acceptance.id) from services.mailinvoice import InvoiceService from applications.good.service import GoodService invoice = acceptance.invoices[0] acceptance.items.delete() invoice.items.delete() for item in items: good_id = item[GOOD_OBJ_ATTR][GOOD_ID_ATTR] fact_count = item[COUNT_ATTR] price_post = item[PRICE_POST_ATTR] price_retail = item[PRICE_RETAIL_ATTR] price_gross = item[PRICE_GROSS_ATTR] good = GoodService.get_good(good_id) InvoiceService.handle_invoiceitem( invoice=invoice, good=good, fact_count=fact_count, price_with_NDS=price_post, full_name=None, name=None, number_local=None, number_global=None, count_order=None, count_postorder=None, count=fact_count, price_without_NDS=None, sum_NDS=None, sum_with_NDS=None, thematic=None, count_whole_pack=None, placer=None, rate_NDS=None, sum_without_NDS=None, price_retail=price_retail, price_gross=price_gross) ac_it = AcceptanceItems() ac_it.good_id = good_id ac_it.acceptance = acceptance ac_it.count = fact_count ac_it.fact_count = fact_count db.session.add(ac_it) debug(u"Обновление фактического кол-ва по новой `прихода` id = '%s' " u"завершено." % acceptance.id)
def get(self, id): try: good = GoodService.get_good(id) except GoodServiceException as err: abort(404, message=unicode(err)) return good
def handle_orderitem(cls, full_name, name, number_local, number_global, date, remission, NDS, price_prev, price_post, order): from applications.good.service import GoodService from applications.commodity.service import CommodityService item = OrderItem() item.full_name = full_name, item.name = name item.number_local = number_local item.number_global = number_global item.date = date item.remission = remission item.NDS = float(NDS.replace("%", "").strip()) item.price_prev = price_prev if price_prev else 0.0 item.price_post = price_post if price_post else 0.0 item.order = order res, comm = CommodityService.get_or_create_commodity( name=name) if res is False: if not number_local and not number_global: comm.numeric = False db.session.add(comm) db.session.flush() res, good = GoodService.get_or_create_commodity_numbers( comm.id, number_local, number_global) good.commodity = comm good.full_name = full_name item.good = good db.session.add(good) db.session.add(item)
def get(self): args = request.args good_id = args['good_id'] price_post = args['price_post'] good = GoodService.get_good(good_id) commodity = good.commodity try: prices = PriceService.prices_parish_to_commodity_price( commodity, float(price_post)) # TODO - кажется тут не вылетит никогда исключение # PriceServiceException except PriceServiceException as exc: debug(unicode(exc)) error(u"Это случилось. resource/price.py") abort(404, message=unicode(exc), code=1) else: return {'items': [{ 'invoice_id': x.invoice_id, 'invoice_str': unicode(x.invoice), 'provider_id': x.invoice.provider_id, 'provider_str': x.invoice.provider.name, 'number_local_from': x.number_local_from, 'number_global_from': x.number_global_from, 'date_from': x.date_from, 'price_post': x.price_post, 'price_retail': x.price.price_retail, 'price_gross': x.price.price_gross } for x in prices]}
def get(self, id): good = GoodService.get_good(id) commodity = good.commodity try: items = PriceService.get_priceparish_strong( commodity_id=commodity.id, number_global=good.number_global, number_local=good.number_local) except NotFindPriceParishExc: items = [] return {'items': items}
def pre_save(self, obj, data): from applications.commodity.service import CommodityService obj.number_local = str(obj.number_local) if obj.number_local else None obj.number_global = str(obj.number_global) if obj.number_global \ else None if obj.commodity_id is None: raise GoodResourceCanon.GoodResourceException( u"Нельзя сохранить товар без номенклатуры.") commodity = CommodityService.get_by_id(obj.commodity_id) try: res, good = GoodService.get_or_create_commodity_numbers( obj.commodity_id, obj.number_local, obj.number_global, obj.id) except GoodServiceException as exc: raise GoodResourceCanon.GoodResourceException(unicode(exc)) if res is False: good.commodity = commodity price_id = data.get('price_id') if price_id: good.price_id = price_id if not data.get('full_name'): full_name = GoodService.full_name(good) else: full_name = obj.full_name good.full_name = full_name if res is True: if commodity.numeric: message = u"В системе уже есть товар с наименованием %s и " \ u"№%s(%s)" % ( commodity.name, obj.number_local, obj.number_global) else: message = u"В системе уже есть безномерной товар с " \ u"наименованием %s" % commodity.name raise GoodResourceCanon.GoodResourceException(message) good = super(GoodResourceCanon, self).pre_save(good, data) return good
def get_item_to_acceptance(cls, invoice_id, acceptance_id): from applications.point_sale.service import PointSaleService from applications.acceptance.service import AcceptanceService acceptance = AcceptanceService.get_by_id(acceptance_id) pointsale = acceptance.pointsale return [{ "id": item.id, "full_name": item.full_name, "good_id": item.good_id, "price_retail": GoodService.get_price( item.good_id).price_retail if GoodService.get_price( item.good_id) else "", "price_gross": GoodService.get_price( item.good_id).price_gross if GoodService.get_price( item.good_id) else "", "count": PointSaleService.item_to_pointsale_good( pointsale.id, item.good_id).count if PointSaleService.item_to_pointsale_good( pointsale.id, item.good_id) else "", } for item in cls.get_items(invoice_id=invoice_id)]
def get_items_acceptance(cls, acc_id, remain=True): from applications.point_sale.service import PointSaleService from applications.acceptance.service import AcceptanceService from applications.waybill.service import WayBillService acceptance = AcceptanceService.get_by_id(acc_id) pointsale = acceptance.pointsale def get_count_remain(remain, item, pointsale_id): if remain: return PointSaleService.item_to_pointsale_good( pointsale.id, item.good_id).count \ if PointSaleService.item_to_pointsale_good( pointsale.id, item.good_id) else "" else: return item.count if acceptance.invoice: return [{ "id": item.id, "full_name": item.full_name, "good_id": item.good_id, "price_without_NDS": item.price_without_NDS, "price_with_NDS": item.price_with_NDS, "price_retail": GoodService.get_price( item.good_id).price_retail if GoodService.get_price( item.good_id) else "", "price_gross": GoodService.get_price( item.good_id).price_gross if GoodService.get_price( item.good_id) else "", "count": get_count_remain(remain, item, pointsale.id), "fact_count": item.fact_count } for item in cls.get_items(invoice_id=acceptance.invoice_id)] elif acceptance.waybill_crud: return [{ "id": item.id, "full_name": item.good.full_name, "good_id": item.good_id, "price_retail": GoodService.get_price( item.good_id).price_retail if GoodService.get_price( item.good_id) else "", "price_gross": GoodService.get_price( item.good_id).price_gross if GoodService.get_price( item.good_id) else "", "count": get_count_remain(remain, item, pointsale.id), } for item in WayBillService.get_items(acceptance.waybill_id)]
def convert_itemitems_to_json(item, type): price = GoodService.get_price(item.good_id) return { 'id': item.id, 'full_name': item.good.full_name, 'good_id': item.good_id, 'count_invoice': item.count, 'price': price.price_retail if type == 1 else price.price_gross, 'price_gross': price.price_gross, 'price_retail': price.price_retail, 'is_approve': True }
def get(self, id): good = GoodService.get_good(id) file_name = str(uuid.uuid4()) + ".pdf" path_to_target = os.path.join(PATH_TO_GENERATE_INVOICE, file_name) path = os.path.join(PATH_WEB, file_name) if good.barcode is None or good.barcode == '': abort(400, message=u"Для печати штрих кода, необходимо указать " u"его!") createBarCodes(path_to_target, str(good.barcode)) return {"link": path}
def handle_returnitem(cls, full_name, name, number_local, number_global, date, date_to, price_without_NDS, price_with_NDS, remission, count_delivery, count_rem, return_inst): from applications.commodity.service import CommodityService from applications.good.service import GoodService item = ReturnItem() item.full_name = full_name item.name = name item.number_local = number_local item.number_global = number_global item.date = date item.date_to = date_to item.price_without_NDS = price_without_NDS item.price_with_NDS = price_with_NDS item.remission = remission item.count_delivery = count_delivery item.count_rem = count_rem item.return_item = return_inst res, comm = CommodityService.get_or_create_commodity( name=name) if res is False: if not number_local and not number_global: comm.numeric = False db.session.add(comm) db.session.flush() try: res, good = GoodService.get_or_create_commodity_numbers( comm.id, number_local, number_global) except GoodArgumentExc as exc: error(u"При обработке позиций возврата возникла " u"ошибка. " + unicode(exc)) raise good.commodity = comm good.full_name = full_name item.good = good db.session.add(good) db.session.add(item)
def create_or_update_prices(cls, invoice_model, data_items): """ Создаем или изменяем цены позиций переданной накладной. """ invoice_id = invoice_model.id debug(u"Начало сохранения цен в позициях накладной %d", invoice_id) from applications.good.service import GoodService from services.mailinvoice import InvoiceService try: for data in data_items: good_id = data['id_good'] commodity_id = int(data['id_commodity']) price_retail = float(data['price_retail']) \ if data['price_retail'] else None price_gross = float(data['price_gross']) \ if data['price_gross'] else None NDS = float(data['NDS']) price_prev = float(data['price_prev']) price_post = float(data['price_post']) good = GoodService.get_good(good_id) number_local = data['number_local'] number_global = data['number_global'] item = InvoiceService.get_item_by_invoice_good(invoice_id, good_id) item.price_retail = price_retail item.price_gross = price_gross db.session.add(item) cls.create_or_update(good, DataToUpdatePrice( id_commodity=commodity_id, price_retail=price_retail, price_gross=price_gross, price_prev=price_prev, price_post=price_post, NDS=NDS, number_local=number_local, number_global=number_global, invoice=invoice_model)) except Exception as err: error( u"Ошибка сохранения цен в позициях накладной %d. %s", invoice_id, unicode(err)) db.session.rollback() raise PriceServiceException(err) else: db.session.commit() debug(u"Конец сохранения цен в позициях накладной %d", invoice_id)
def upgrade_items(cls, waybillreturn, items): from applications.price.service import PriceService from applications.good.service import GoodService waybillreturn.items.delete() db.session.add(waybillreturn) for it in items: good = GoodService.get_good(it.good_id) if waybillreturn.type == RETAIL: if not good.price_id or not PriceService.get_price( good.price_id).price_retail: raise WayBillReturnService.WayBillReturnServiceExc( u"Товар без розничной цены. %s" % good.full_name) else: if not good.price_id or not PriceService.get_price( good.price_id).price_gross: raise WayBillReturnService.WayBillReturnServiceExc( u"Товар без оптовой цены. %s" % good.full_name) it.waybill = waybillreturn db.session.add(it)
def save_from_json(cls, date, items, provider_id=None, invoice=None): """ Сохраняем накладную с позициями. Для редактирования надо передать инстанс накладной в переменную invoice. """ from applications.price.service import DataToUpdatePrice, PriceService from applications.point_sale.service import PointSaleService try: if invoice: invmodel = invoice else: provider = ProviderService.get_by_id(provider_id) invmodel = InvoiceService.create_invoice( number=InvoiceService.generate_number(date), date=date, provider=provider, sum_without_NDS=None, sum_with_NDS=None, sum_NDS=None, weight=None, responsible=None) db.session.add(invmodel) if invoice: pointsale = invoice.acceptance.pointsale for item in invmodel.items: pointsale_item = PointSaleService.item_to_pointsale_good( pointsale.id, item.good_id) pointsale_item.count -= item.count db.session.add(pointsale_item) invmodel.items.delete() db.session.add(invmodel) for item in items: good = GoodService.get_good(item['good_id']) name = good.commodity.name number_local = good.number_local number_global = good.number_global full_name = GoodService.generate_name( name, number_local, number_global) invoice = invmodel count_order= None count_postorder = None count = item['count_invoice'] if 'count_invoice' in item \ else None price_without_NDS = item['price_pre'] if 'price_pre' in item \ else None price_with_NDS = item['price_post'] if 'price_post' in item \ else None sum_without_NDS = None sum_NDS = None rate_NDS = item['NDS'] if 'NDS' in item else None sum_with_NDS = None thematic = None count_whole_pack = None placer = None fact_count = None cls.handle_invoiceitem( full_name, name, number_local, number_global, invoice, count_order, count_postorder, count, price_without_NDS, price_with_NDS, sum_without_NDS, sum_NDS, rate_NDS, sum_with_NDS, thematic, count_whole_pack, placer, good, fact_count) if 'price_retail' in item or 'price_gross' in item: PriceService.create_or_update(good, DataToUpdatePrice( id_commodity=good.commodity_id, price_retail=item['price_retail'], price_gross=item['price_gross'], price_prev=item['price_prev'] if 'price_prev' in item else None, price_post=item['price_post'], NDS=item['NDS'] if 'NDS' in item else None, number_local=number_local, number_global=number_global, invoice=invmodel)) except Exception as exc: db.session.rollback() error(unicode(exc)) raise InvoiceService.InvoiceServiceException(unicode(exc)) else: db.session.commit() return invmodel
def handle_invoiceitem( cls, full_name, name, number_local, number_global, invoice, count_order, count_postorder, count, price_without_NDS, price_with_NDS, sum_without_NDS, sum_NDS, rate_NDS, sum_with_NDS, thematic, count_whole_pack, placer, good=None, fact_count=None, price_retail=None, price_gross=None): """ Обработка позиции накладной. Сохраняем в БД позицию. Создаем товар в системе. """ from applications.commodity.service import CommodityService invitem = InvoiceItem() invitem.full_name = full_name invitem.count_order = count_order invitem.count_postorder = count_postorder invitem.count = count invitem.price_without_NDS = price_without_NDS invitem.price_with_NDS = price_with_NDS invitem.sum_without_NDS = sum_without_NDS invitem.sum_with_NDS = sum_with_NDS invitem.sum_NDS = sum_NDS invitem.rate_NDS = rate_NDS invitem.count_whole_pack = count_whole_pack invitem.placer = placer invitem.invoice = invoice invitem.price_gross = price_gross invitem.price_retail = price_retail if good: invitem.good = good invitem.name = good.commodity.name invitem.number_local = good.number_local invitem.number_global = good.number_global invitem.thematic=good.commodity.thematic if fact_count: invitem.fact_count = fact_count else: invitem.name=name invitem.number_local=number_local invitem.number_global=number_global invitem.thematic=thematic res, comm = CommodityService.get_or_create_commodity( name=name, thematic=thematic) if res is False: if not number_local and not number_global: comm.numeric = False db.session.add(comm) db.session.flush() try: res, good = GoodService.get_or_create_commodity_numbers( comm.id, number_local, number_global) except GoodArgumentExc as exc: error(u"При обработке позиций накладной возникла ошибка. " + unicode(exc)) raise good.commodity = comm good.full_name = full_name invitem.good = good db.session.add(good) db.session.add(invitem)
def report_multi(cls, ids): import uuid import os from config import PATH_TO_GENERATE_INVOICE, PATH_WEB from excel.output import PATH_TEMPLATE from applications.good.service import GoodService COUNT_ROW = 42 COUNT_ROW2 = 91 file_name = str(uuid.uuid4()) + ".xlsx" path_to_target = os.path.join(PATH_TO_GENERATE_INVOICE, file_name) path = os.path.join(PATH_WEB, file_name) report = SpreadsheetReport(os.path.join( PATH_TEMPLATE, 'print_invoice2.xlsx')) for id in ids: waybill = WayBillService.get_by_id(id) sec_sub = report.get_section("sec1") sec_items = report.get_section("secitem") sec_data = {} sec_data['number'] = waybill.number sec_data['date'] = waybill.date.strftime('%d.%m.%Y').decode("utf-8") sec_data['point'] = waybill.pointsale_from.name sec_data['typeInv'] = waybill.type sec_data['rec'] = waybill.rec sec_sub.flush(sec_data) if waybill.type == RETAIL: for it in waybill.items: sec_items_data = { 'name': it.good.full_name, 'count': it.count or "", 'price_pay': GoodService.get_price(it.good_id).price_retail, 'mul': it.count * GoodService.get_price( it.good_id).price_retail if it.count else ''} sec_items.flush(sec_items_data) if waybill.items.count() <= COUNT_ROW: for i in xrange(COUNT_ROW - waybill.items.count()): sec_items.flush({'name': '', 'count': '', 'price_pay': '', 'mul': ''}) elif waybill.items.count() <= COUNT_ROW2: for i in xrange(COUNT_ROW2 - waybill.items.count()): sec_items.flush({'name': '', 'count': '', 'price_pay': '', 'mul': ''}) else: for it in waybill.items: sec_items_data = {'name': it.good.full_name, 'count': it.count or "", 'price_pay': GoodService.get_price(it.good_id).price_gross, 'mul': it.count * GoodService.get_price( it.good_id).price_gross if it.count else ''} sec_items.flush(sec_items_data) if waybill.items.count() <= COUNT_ROW: for i in xrange(COUNT_ROW - waybill.items.count()): sec_items.flush({'name': '', 'count': '', 'price_pay': '', 'mul': ''}) elif waybill.items.count() <= COUNT_ROW2: for i in xrange(COUNT_ROW2 - waybill.items.count()): sec_items.flush({'name': '', 'count': '', 'price_pay': '', 'mul': ''}) report.build(path_to_target) return path