Esempio n. 1
0
    def process_state_using_ps_data(self, order_state):
        """Process Sale state as per the current state

        :param order_state: Site order state corresponding to ps order state
        """
        Sale = Pool().get('sale.sale')

        # Do not process sale if sale has exception
        if self.has_channel_exception:
            return

        self.channel.get_prestashop_client()

        # Cancel the order if its cancelled on prestashop
        if order_state.order_state == 'sale.cancel':
            Sale.cancel([self])
            return

        # Confirm and process the order in any other case
        Sale.quote([self])
        Sale.confirm([self])

        if order_state.order_state != 'sale.confirmed':
            # XXX: To mark sale as Done, sale must be in Processing state
            # as marking sale as Done is part of transition workflow now,
            # which allows only processed sale to be marked as Done.
            # But not sure if calling proceed before process is the right
            # way to do.
            Sale.proceed([self])
            Sale.process([self])
Esempio n. 2
0
    def process_state_using_ps_data(self, order_state):
        """Process Sale state as per the current state

        :param order_state: Site order state corresponding to ps order state
        """
        Sale = Pool().get('sale.sale')

        # Do not process sale if sale has exception
        if self.has_channel_exception:
            return

        self.channel.get_prestashop_client()

        # Cancel the order if its cancelled on prestashop
        if order_state.order_state == 'sale.cancel':
            Sale.cancel([self])
            return

        # Confirm and process the order in any other case
        Sale.quote([self])
        Sale.confirm([self])

        if order_state.order_state != 'sale.confirmed':
            # XXX: To mark sale as Done, sale must be in Processing state
            # as marking sale as Done is part of transition workflow now,
            # which allows only processed sale to be marked as Done.
            # But not sure if calling proceed before process is the right
            # way to do.
            Sale.proceed([self])
            Sale.process([self])
Esempio n. 3
0
    def process_to_channel_state(self, channel_state):
        """
        Process the sale in tryton based on the state of order
        when its imported from channel.

        :param channel_state: State on external channel the order was imported.
        """
        Sale = Pool().get('sale.sale')

        data = self.channel.get_tryton_action(channel_state)

        if self.state == 'draft':
            self.invoice_method = data['invoice_method']
            self.shipment_method = data['shipment_method']
            self.save()

        if data['action'] in ['process_manually', 'process_automatically']:
            if self.state == 'draft':
                Sale.quote([self])
            if self.state == 'quotation':
                Sale.confirm([self])

        if data['action'] == 'process_automatically' and \
                self.state == 'confirmed':
            Sale.process([self])

        if data['action'] == 'import_as_past' and self.state == 'draft':
            # XXX: mark past orders as completed
            self.state = 'done'
            self.save()
            # Update cached values
            Sale.store_cache([self])
    def checkout(self):
        '''Submit of default checkout

        A GET to the method will result in passing of control to begin as
        that is basically the entry point to the checkout

        A POST to the method will result in the confirmation of the order and
        subsequent handling of data.
        '''
        cart_obj = Pool().get('nereid.cart')
        sale_obj = Pool().get('sale.sale')

        cart = cart_obj.open_cart()
        if not cart.sale:
            # This case is possible if the user changes his currency at
            # the point of checkout and the cart gets cleared.
            return redirect(url_for('nereid.cart.view_cart'))

        sale = cart.sale
        if not sale.lines:
            flash(_("Add some items to your cart before you checkout!"))
            return redirect(url_for('nereid.website.home'))
        if request.method == 'GET':
            return (self._begin_guest() if request.is_guest_user \
                else self._begin_registered())

        elif request.method == 'POST':
            form, do_process = self._submit_guest() if request.is_guest_user \
                else self._submit_registered()
            if do_process:
                # Process Shipping
                self._process_shipment(sale, form)

                # Process Payment, if the returned value from the payment
                # is a response object (isinstance) then return that instead
                # of the success page. This will allow reidrects to a third 
                # party gateway or service to collect payment.
                response = self._process_payment(sale, form)
                if isinstance(response, BaseResponse):
                    return response

                if sale.state == 'draft':
                    # Ensure that the order date is that of today
                    cart_obj.check_update_date(cart)
                    # Confirm the order
                    sale_obj.quote([sale.id])
                    sale_obj.confirm([sale.id])

                flash(_("Your order #%(sale)s has been processed", sale=sale.reference))
                if request.is_guest_user:
                    return redirect(url_for('nereid.website.home'))
                else:
                    return redirect(
                        url_for(
                            'sale.sale.render', sale=sale.id, 
                            confirmation=True
                        )
                    )

            return render_template('checkout.jinja', form=form, cart=cart)
Esempio n. 5
0
    def process_to_channel_state(self, channel_state):
        """
        Process the sale in tryton based on the state of order
        when its imported from channel

        :param channel_state: State on external channel the order was imported
        """
        Sale = Pool().get('sale.sale')
        Shipment = Pool().get('stock.shipment.out')

        data = self.channel.get_tryton_action(channel_state)

        if data['action'] in ['process_manually', 'process_automatically']:
            Sale.quote([self])
            Sale.confirm([self])

        if data['action'] == 'process_automatically':
            Sale.process([self])
            for shipment in self.shipments:
                if shipment.state == 'draft':
                    Shipment.wait([shipment])
                if shipment.state == 'waiting':
                    Shipment.assign_try([shipment])

        if data['action'] == 'import_as_past':
            # XXX: mark past orders as completed
            self.state = 'done'
            self.save()
Esempio n. 6
0
    def process_to_channel_state(self, channel_state):
        """
        Process the sale in tryton based on the state of order
        when its imported from channel

        :param channel_state: State on external channel the order was imported
        """
        Sale = Pool().get('sale.sale')
        Shipment = Pool().get('stock.shipment.out')

        data = self.channel.get_tryton_action(channel_state)

        if data['action'] in ['process_manually', 'process_automatically']:
            Sale.quote([self])
            Sale.confirm([self])

        if data['action'] == 'process_automatically':
            Sale.process([self])
            for shipment in self.shipments:
                if shipment.state == 'draft':
                    Shipment.wait([shipment])
                if shipment.state == 'waiting':
                    Shipment.assign_try([shipment])

        if data['action'] == 'import_as_past':
            # XXX: mark past orders as completed
            self.state = 'done'
            self.save()
Esempio n. 7
0
    def process_sale_using_magento_state(self, magento_state):
        """
        Process the sale in tryton based on the state of order
        when its imported from magento

        :param magento_state: State on magento the order was imported in
        """
        Sale = Pool().get('sale.sale')

        data = self.channel.get_tryton_action(magento_state)

        if data['action'] in ['process_manually', 'process_automatically']:
            Sale.quote([self])
            Sale.confirm([self])

        if data['action'] == 'process_automatically':
            Sale.process([self])
Esempio n. 8
0
    def process_sale_using_magento_state(self, magento_state):
        """
        Process the sale in tryton based on the state of order
        when its imported from magento

        :param magento_state: State on magento the order was imported in
        """
        Sale = Pool().get('sale.sale')

        data = self.channel.get_tryton_action(magento_state)

        if data['action'] in ['process_manually', 'process_automatically']:
            Sale.quote([self])
            Sale.confirm([self])

        if data['action'] == 'process_automatically':
            Sale.process([self])
Esempio n. 9
0
    def process_fba_order(self):
        """
        Process FBA Orders as they are imported as past orders
        and handle their shipments.
        """
        Sale = Pool().get('sale.sale')
        Shipment = Pool().get('stock.shipment.out')

        Sale.quote([self])
        Sale.confirm([self])
        Sale.process([self])

        for shipment in self.shipments:
            if shipment.state == 'draft':
                Shipment.wait([shipment])
            if shipment.state == 'waiting':
                Shipment.assign([shipment])
            if shipment.state == 'assigned':
                Shipment.pack([shipment])
            if shipment.state == 'packed':
                Shipment.done([shipment])
Esempio n. 10
0
    def process_sale_using_magento_state(self, magento_state):
        """
        Process the sale in tryton based on the state of order
        when its imported from magento

        :param magento_state: State on magento the order was imported in
        """
        Sale = Pool().get('sale.sale')

        data = MagentoOrderState.get_tryton_state(magento_state)

        # If order is canceled, just cancel it
        if data['tryton_state'] == 'sale.cancel':
            Sale.cancel([self])
            return

        # Order is not canceled, move it to quotation
        Sale.quote([self])
        Sale.confirm([self])

        if data['tryton_state'] not in ['sale.quotation', 'sale.confirmed']:
            Sale.process([self])
Esempio n. 11
0
    def confirm_cart(cls, cart):
        '''
        Confirm the sale, clear the sale from the cart
        '''
        Sale = Pool().get('sale.sale')

        sale = cart.sale
        Sale.quote([cart.sale])
        Sale.confirm([cart.sale])

        cart.sale = None
        cart.save()

        # Redirect to the order confirmation page
        flash(_(
            "Your order #%(sale)s has been processed",
            sale=sale.reference
        ))

        return redirect(url_for(
            'sale.sale.render', active_id=sale.id, confirmation=True,
            access_code=sale.guest_access_code,
        ))
Esempio n. 12
0
    def confirm_cart(cls, cart):
        '''
        Confirm the sale, clear the sale from the cart
        '''
        Sale = Pool().get('sale.sale')

        sale = cart.sale
        Sale.quote([cart.sale])
        Sale.confirm([cart.sale])

        cart.sale = None
        cart.save()

        # Redirect to the order confirmation page
        flash(_(
            "Your order #%(sale)s has been processed",
            sale=sale.reference
        ))

        return redirect(url_for(
            'sale.sale.render', active_id=sale.id, confirmation=True,
            access_code=sale.guest_access_code,
        ))
Esempio n. 13
0
    def do_create_(self, action):
        Product = Pool().get('product.product')
        ProductQuantity = Pool().get('product_quantity')
        Purchase = Pool().get('purchase.purchase')
        Company = Pool().get('company.company')
        Date = Pool().get('ir.date')
        Move = Pool().get('stock.move')
        Lot = Pool().get('stock.lot')
        today = str(Date.today())
        Config = Pool().get('purchase.configuration')
        config = Config(1)
        company = Company.search([('id', '=', Transaction().context['company'])
                                  ])
        currency = company[0].currency
        Invoice = Pool().get('account.invoice')
        ShipmentIn = Pool().get('stock.shipment.in')
        PurchaseBills = Pool().get('purchase_bills')
        ShipmentInReturn = Pool().get('stock.shipment.in.return')
        data = {}
        for state_name, state in self.states.iteritems():
            if isinstance(state, StateView):
                data[state_name] = getattr(self, state_name)._default_values
        message = ''
        for each in data['start']['stock_return_lines']:
            if each['ensure'] == True and data['start'][
                    'order_category'] == 'return':
                shipmentinreturn = ShipmentInReturn.search([
                    ('id', '=', each['return_id']), ('state', '!=', 'done')
                ])
                if not shipmentinreturn:
                    message = u'该单号已被处理,请退出后重新查询。'
                    continue
                whether_move = Move.assign_try(
                    [Move(shipmentinreturn[0].moves[0].id)],
                    grouping=('product', 'lot'))
                if not whether_move:
                    message += shipmentinreturn[0].moves[
                        0].product.code + shipmentinreturn[0].moves[
                            0].product.name + u'-批次:' + Lot(
                                shipmentinreturn[0].moves[0].lot
                            ).number + u'实际数量有变,请删除该行项目后重新输入\n'
                    continue
                ShipmentInReturn.assign(shipmentinreturn)
                ShipmentInReturn.done(shipmentinreturn)
            if each['ensure'] == True and data['start'][
                    'order_category'] == 'purchase':
                purchase_bills = PurchaseBills.search([('id', '=',
                                                        each['purchase_id'])])
                purchase = Purchase.search([
                    ('number', '=', purchase_bills[0].order_code)
                ])  # ,('state', '!=', 'processing')
                if not purchase:
                    message = u'该单号已被处理,请退出后重新查询。'
                    continue
                PurchaseBills.write(purchase_bills, {'state': 'done'})
                Purchase.quote(purchase)
                Purchase.confirm(purchase)
                Purchase.process(purchase)
                moves = Move.search([
                    ('product', '=', purchase_bills[0].product.id),
                    ('purchase', '=', purchase_bills[0].order_code),
                    ('state', '=', 'draft')
                ])
                Move.write(
                    moves, {
                        'outgoing_audit': '02',
                        'lot': purchase_bills[0].lot.id,
                        'quantity': purchase_bills[0].shipment_quantity,
                        'move_type': '101'
                    })
                lv = {}
                if moves != []:
                    lv['incoming_moves'] = [['add', [moves[0].id]]]
                lv['reference'] = ''
                lv['planned_date'] = today
                lv['return_shipment'] = purchase_bills[0].return_shipment
                lv['company'] = Transaction().context.get('company')
                lv['effective_date'] = None
                lv['cause'] = '00'
                lv['warehouse'] = config.warehouse.id
                lv['supplier'] = purchase_bills[0].party.id
                lv['inventory_moves'] = []
                shipments = ShipmentIn.create([lv])
                shipment = ShipmentIn.search([('id', '=', shipments[0].id)])
                ShipmentIn.receive(shipment)
                ShipmentIn.done(shipment)
                invoices = Invoice.search([
                    ('state', '=', 'draft'),
                    ('id', 'in', [
                        ids.id
                        for ids in [i
                                    for i in [k.invoices for k in purchase]][0]
                    ])
                ])
                Invoice.write(
                    invoices, {
                        'invoice_date': purchase_bills[0].purchase_create_time,
                        'reference': purchase_bills[0].invoice_code,
                        'description':
                        purchase_bills[0].return_shipment.number,
                        'amount': purchase_bills[0].amount_of_real_pay
                    })
                Invoice.validate_invoice(invoices)
                Invoice.validate_invoice(invoices)

                product_quantities = ProductQuantity.search(
                    [('product', '=', purchase_bills[0].product.id)],
                    order=[["sequence", "ASC"]])
                move = {
                    u'comment': u'',
                    u'outgoing_audit': u'00',
                    u'product': purchase_bills[0].product.id,
                    u'from_location': config.warehouse.storage_location.id,
                    u'invoice_lines': [],
                    u'starts': u'05',
                    u'move_type': '000',
                    u'company': Transaction().context.get('company'),
                    u'unit_price': purchase_bills[0].product.cost_price,
                    u'currency': currency.id,
                    u'reason': '00',
                    u'lot': purchase_bills[0].lot.id,
                    u'planned_date': today,
                    u'uom': purchase_bills[0].product.default_uom.id,
                    u'origin': None,  # u'sale.line,-1',
                }
                move_quantity = purchase_bills[0].shipment_quantity
                for product_quantity in product_quantities:
                    with Transaction().set_context(
                            stock_date_end=Date.today()):  # 查看具体库下面的批次对应的数量
                        warehouse_quant = Product.products_by_location(
                            [product_quantity.location.id],
                            [purchase_bills[0].product.id],
                            with_childs=True)
                        move['to_location'] = product_quantity.location.id
                        warehouse_quantity = warehouse_quant[(
                            product_quantity.location.id,
                            purchase_bills[0].product.id)]
                        if product_quantity.quantity - warehouse_quantity >= move_quantity:
                            move['quantity'] = move_quantity
                            if move['quantity'] < 0:
                                self.raise_user_error(u'当前库存已超过最大库存!')
                            moves = Move.create([move])
                            Move.do(moves)
                            break
                        else:
                            move[
                                'quantity'] = product_quantity.quantity - warehouse_quantity
                            if move['quantity'] < 0:
                                self.raise_user_error(u'当前库存已超过最大库存!')
                            move_quantity = move_quantity + warehouse_quantity - product_quantity.quantity
                            moves = Move.create([move])
                            Move.do(moves)
        if message:
            self.raise_user_error(message)
        return action, {}
Esempio n. 14
0
    def model_copy(cls, subscription_id):
        Cron = Pool().get('ir.cron')
        History = Pool().get('training.subscription.history')
        Invoice = Pool().get('account.invoice')
        Sale = Pool().get('sale.sale')
        SaleInvoice = Pool().get('sale.sale-account.invoice')
        
        subscription = cls(subscription_id)
        logger = logging.getLogger('training_subscription')
        number_calls = subscription.number_calls
        remaining = Cron.browse([subscription.cron.id])[0].number_calls
        actual = number_calls - remaining + 1
        model_id = subscription.model_source and subscription.model_source.id \
                or False
        if model_id:
            Model = Pool().get(subscription.model_source.__name__)
            default = {'state':'draft'}
            #default['subscription_code'] = subscription.model_source.subscription_code + ' ' +str(actual)
            default['subscription_code'] = subscription.model_source.subscription_code

            try:
                model = Model.copy([subscription.model_source], default)
            except:
                history_vals = {
                    'log': cls.raise_user_error(
                        error='error_creating',
                        error_args=subscription.model_source.__name__, 
                        raise_exception=False)
                }
            else:
                history_vals = {
                    'log': cls.raise_user_error(
                        error='created_successfully',
                        error_args=subscription.model_source.__name__, 
                        raise_exception=False)
                }
                history_vals['document'] = (subscription.model_source.__name__,
                                        model[0].id)
            History.create([history_vals])
            
            sales = Sale.search([
                         ('id','=',model[0].id)
                         ])
            
            for sale in sales:
                Sale.quote([sale])
                Sale.confirm([sale])
                Sale.process([sale])
                
                saleinvoices = SaleInvoice.search([
                    ('sale', '=', sale.id),
                    ])
                invoices = Invoice.search( [
                    ('id','=',saleinvoices[0].invoice.id)
                    ])
                Invoice.write(invoices, {
                    'reference': sale.subscription_code,
                    'invoice_date': sale.sale_date,
                    })
                Invoice.post(invoices)
                
                if invoices:
                    for invoice in invoices:
                        cls.write([subscription], 
                                           {'sales': [('add', [sale.id])],
                                           'invoices': [('add', [invoice.id])]
                                               })

            # If it is the last cron execution, set the state of the
            # subscription to done
            if remaining == 1:
                subscription.write([subscription], {'state': 'done'})
        else:
            logger.error('Document in subscription %s not found.\n' % \
                         subscription.code)