Example #1
0
    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)
Example #2
0
    def status(cls, acceptance, status):
        from applications.point_sale.service import PointSaleService
        from applications.price.service import PriceService, DataToUpdatePrice
        debug(u"Смена статуса `прихода` id = '%s' с %s на %s." % (
            acceptance.id, acceptance.status, StatusType[status]))

        if status == DRAFT:
            if acceptance.type == NEW:
                debug(u"Переход `прихода` id = '%s' в статус 'Черновик' и "
                      u"типом 'Новая' сопровождается удалением накладной."
                      % acceptance.id)
                acceptance.items.delete()
                acceptance.invoice.items.delete()
                db.session.delete(acceptance.invoice)

        if status == IN_PROG:
            if acceptance.type == MAIL:
                cls.initial_acceptance_from_mail(acceptance)
            elif acceptance.type == NEW:
                cls.initial_acceptance_from_custom(acceptance)

        if status == VALIDATED:
            if acceptance.type == MAIL:
                for item in acceptance.items:
                    if item.fact_count:
                        PointSaleService.sync_good_increment(
                            acceptance.pointsale_id, item.good_id,
                            item.fact_count)
            elif acceptance.type == NEW:
                invoice = acceptance.invoices[0]
                for item in invoice.items:
                    good = item.good

                    PriceService.create_or_update(good, DataToUpdatePrice(
                        id_commodity=good.commodity_id,
                        price_retail=item.price_retail,
                        price_gross=item.price_gross,
                        price_prev=None,
                        price_post=item.price_with_NDS,
                        NDS=None,
                        number_local=good.number_local,
                        number_global=good.number_global,
                        invoice=invoice))
                    if item.fact_count:
                        PointSaleService.sync_good_increment(
                            acceptance.pointsale_id, item.good_id,
                            item.fact_count)
        old_status = acceptance.status
        acceptance.status = status
        debug(u"Смена статуса `прихода` id = '%s' с %s на %s завершено." % (
            acceptance.id, old_status, StatusType[status]))
Example #3
0
    def post(self):
        data = request.json['data']

        prices = data['items']
        invoice_id = data['invoice_id']
        invoice = InvoiceService.get_by_id(invoice_id)
        try:
            PriceService.create_or_update_prices(invoice, prices)
            db.session.commit()
        except PriceServiceException as err:
            debug(unicode(err))
            abort(404, message=unicode(err))
        except Exception as exc:
            error(unicode(exc))
            raise
        return "ok"
Example #4
0
    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]}
Example #5
0
    def post(self):
        data = request.json['data']

        prices = data['items']
        invoice_id = data['invoice_id']
        mail = MailInvoiceService.get_mail(invoice_id)
        invoice = mail.invoice
        try:
            PriceService.create_or_update_prices(invoice, prices)
            mail.is_handling = True
            db.session.add(mail)
            db.session.commit()
        except PriceServiceException as err:
            debug(unicode(err))
            abort(404, message=unicode(err))
        except Exception as exc:
            error(unicode(exc))
            raise
        return "ok"
Example #6
0
    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}
Example #7
0
    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)
Example #8
0
def _stub(invoice):
    from applications.price.service import PriceService
    from models.invoiceitem import InvoiceItem
    items = PriceService.generate_price_stub(
        invoice.items.order_by(asc(InvoiceItem.id)))

    return {'items': [{
        'id_commodity': it.id_commodity,
        'id_good': it.id_good,
        'full_name': it.full_name,
        'number_local': it.number_local,
        'number_global': it.number_global,
        'NDS': it.NDS,
        'price_prev': it.price_prev,
        'price_post': it.price_post,
        'price_retail': it.price_retail,
        'price_gross': it.price_gross,
        'price_retail_recommendation': it.price_retail_recommendation,
        'price_gross_recommendation': it.price_gross_recommendation,
        'is_change': it.is_change
    } for it in items]}
Example #9
0
    def invoice_change_price(self):
        """
        Меняется ли цена у товара при приходе накладной с измененными ценами.
        """
        ITEMS = (
            (u"Men's Health №11(196)", 95.0, 120.0),
            (u"Men's Health/мини формата/№11(117)", 86.0, 105.0),
            (u"Ума палата.Спецвыпуск.Календарь Год козы б/н 2015", 24.0, 30.0),
            (u"Ума палата.Спецвыпуск.Календарь Гороскоп б/н 2015", 23.0, 29.0),
            (u'Цифровые сканворды №42(680)', 14.0, 17.0),
            (u'Числовые сканворды №42(466)', 11.0, 14.0),
            (u"Моя семья №41(735)", 22.0, 26.0)
        )

        CIP_SCAN = u'Цифровые сканворды №42(680)'
        CH_SCAN = u'Числовые сканворды №42(466)'
        MN = u"Men's Health №12(197)"
        MN_MINI = u"Men's Health/мини формата/№12(118)"
        MIND_PAL = u"Ума палата.Спецвыпуск.Календарь Год козы б/н 2015"
        MIND_GOR = u"Ума палата.Спецвыпуск.Календарь Гороскоп б/н 2015"

        PRICE_CH = {
            MN_MINI: (90.0, 110.0),
            MIND_PAL: (25.0, 32.0)
        }

        #проверка вычисления изменения цены товара
        ITEM_CHANGE_PRICE = (
            (CIP_SCAN, False),
            (CH_SCAN, True),
            (MN, True),
            (MN_MINI, True),
            (MIND_PAL, True),
            (MIND_GOR, True)
        )

        #проверка создания новой цены
        ITEM_NEW_PRICE = (
            (CIP_SCAN, False),
            (CH_SCAN, False),
            (MN, False),
            (MN_MINI, True),
            (MIND_PAL, True),
            (MIND_GOR, False)
        )

        #принимаем накладную исходную
        self.mailinvoice_provider.handle_invoice(self.mail_stub.date_, self.FILE_NAME, 1)
        invoice = Invoice.query.first()

        for item in ITEMS:
            name, _, _ = item
            inv_item = self.mailinvoice_provider._get_invoiceitem(invoice.id, name)
            price = PriceService.generate_price_stub_item(inv_item)
            self.assertEqual(price.is_change, False)
        #раставляем цены на некоторые товары
        self.mailinvoice_provider.price_invoice(invoice.id, datas=ITEMS)

        #принимает накладную с измененными ценами
        self.mailinvoice_provider.handle_invoice(self.mail_stub2.date_, self.FILE_NAME2, 2)
        invoice2 = Invoice.query.filter(
            Invoice.id!=invoice.id
        ).one()
        #проверяем, оповещает ли система об измененных ценах
        for item in ITEM_CHANGE_PRICE:
            name, is_ch = item
            inv_item = self.mailinvoice_provider._get_invoiceitem(invoice2.id, name)
            price = PriceService.generate_price_stub_item(inv_item)
            self.assertEqual(price.is_change, is_ch)
        #сохраняем новые цены

        self.mailinvoice_provider.price_invoice(invoice2.id, datas=[(x, PRICE_CH[x][0], PRICE_CH[x][1]) for x in PRICE_CH])

        for item in ITEM_NEW_PRICE:
            name, new_pr = item
            inv_item = self.mailinvoice_provider._get_invoiceitem(invoice2.id, name)
            good = self.mailinvoice_provider._get_good(invoice2.id, name)
            prices_parish = PriceParish.query.filter(
                PriceParish.commodity_id == good.commodity.id,
            )
            self.assertEqual(prices_parish.count(), 2 if new_pr else 1)
            if new_pr and name in PRICE_CH:
                prices_gross, price_retail = PRICE_CH[name]
                self.assertEqual(float(good.price.price_retail), price_retail)
                self.assertEqual(float(good.price.price_gross), prices_gross)
Example #10
0
 def get_price(cls, good_id):
     from applications.price.service import PriceService
     good = cls.get_good(good_id)
     if good.price_id:
         return PriceService.get_price(good.price_id)
Example #11
0
 def get(self):
     return {'items': PriceService.get_all()}
Example #12
0
    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