Exemplo n.º 1
0
    def edi_import_orders_handig_validator(self, ids):
        _logger.debug("Validating handig order")

        # Read the EDI Document
        edi_db = self.env['edi.tools.edi.document.incoming']
        document = edi_db.browse(ids)
        document.ensure_one()

        try:
            data = json.loads(document.content)
            if not data:
                raise EdiValidationError('EDI Document is empty.')
        except Exception:
            raise EdiValidationError('Content is not valid JSON.')

        if not 'number' in data:
            raise EdiValidationError('Could not find field: number.')

        if self.env['sale.order'].search([('client_order_ref', '=',
                                           data["number"])]):
            raise EdiValidationError('Sale order exists with the same number.')

        unknown_eans = []
        for line in data['line_items']:
            product = self.env['product.product'].search(
                [('barcode', '=', line['product']['sku'])], limit=1)
            if not product:
                unknown_eans.append(line['product']['sku'])

        if unknown_eans:
            raise EdiValidationError('Product(s) with ean %s unknown.' %
                                     ', '.join(unknown_eans))

        # If we get all the way to here, the document is valid
        return True
Exemplo n.º 2
0
    def edi_import_essers_pclo_validator(self, document_ids):
        ORDER_NUMBER = 'Ordernummer EDI'
        ORDER_LINE_NUMBER = 'ORIGINAL'

        move_db = self.env['stock.move']
        edi_db = self.env['edi.tools.edi.document.incoming']

        document = edi_db.browse(document_ids)
        document.ensure_one()

        content = self.cleanup_pclo_file(document.content)
        reader = csv.DictReader(content, delimiter=';', quotechar='"', skipinitialspace=True)

        sorted_rows = sorted(reader, key=lambda row: (row[ORDER_NUMBER], row[ORDER_LINE_NUMBER]))
        for delivery_number, rws in groupby(sorted_rows, lambda row: row[ORDER_NUMBER]):
            rows = list(rws)
            delivery = self.env['stock.picking'].search([('name', '=', delivery_number.replace('_', '/'))], limit=1)

            if not delivery:
                raise EdiValidationError("Delivery %s doesn't exist" % (delivery_number.replace('_', '/')))

            #moves_not_assigned = delivery.move_lines.filtered(lambda ml: ml.state != 'assigned')
            #if moves_not_assigned:
            #    raise EdiValidationError("Move lines present in delivery %s which don't have status assigned" % (delivery.name))

            no_matching_move_line_for_edi_sequence = []
            for row in rows:
                move = delivery.move_lines.filtered(lambda ml: ml.edi_sequence == row[ORDER_LINE_NUMBER])
                if not move:
                    no_matching_move_line_for_edi_sequence.append(row[ORDER_LINE_NUMBER])

            if no_matching_move_line_for_edi_sequence:
                raise EdiValidationError("No move lines are found for following edi_sequences in delivery %s.<br/>%s" % (delivery.name, "<br/>".join(no_matching_move_line_for_edi_sequence)))
        _logger.info('pclo validator: no errors') 
        return True
Exemplo n.º 3
0
    def edi_import_example_saleorder_validator(self, document_id):
        document = self.env['edi.tools.edi.document.incoming'].browse(document_id)

        try:
            data = json.loads(document.content)
        except Exception as e:
            raise EdiValidationError('Content is not valid JSON. %s' % (e))

        for line in data.get('lines', []):
            if not line.get('ean13'):
                raise EdiValidationError('EAN13 missing on line')
            product = self.env['product.product'].search([('ean13', '=', line.get('ean13'))], limit=1)
            if not product:
                raise EdiValidationError('There is no product with ean13 number %s' % (line.get('ean13')))
Exemplo n.º 4
0
    def edi_import_order_xml_validator(self, document_ids):
        _logger.debug("Validating XML document")

        # Read the EDI Document
        edi_db = self.env['edi.tools.edi.document.incoming']
        document = edi_db.browse(document_ids)
        document.ensure_one()

        # Convert the document to JSON
        try:
            content = xmltodict.parse(document.content)
            #valid = content[InitialPurchaseOrder]
            #valid = content[InitialPurchaseOrder][PurchaseOrderHeader]
        except Exception:
            raise EdiValidationError(
                'Content is not valid XML or the structure deviates from what is expected.'
            )

        if not 'InitialPurchaseOrder' in content:
            _logger.debug(
                "XML Order document invalid, no InitialPurchaseOrder segment")
            raise EdiValidationError(
                'XML Order document invalid, no InitialPurchaseOrder segment')

        if not 'DestinationName1' in content['InitialPurchaseOrder'][
                'PurchaseOrderHeader']['IdDestination']:
            _logger.debug(
                "XML Order document invalid, no Destination Name in IdDestination"
            )
            raise EdiValidationError(
                'XML Order document invalid, no Destination Name in IdDestination'
            )
        else:
            header = content['InitialPurchaseOrder']['PurchaseOrderHeader']
            delivery_partner = self.env['res.partner'].search([
                ('name', '=', header['IdDestination']['DestinationName1'])
            ])
            _logger.info("XML Delivery Partner: %s",
                         header['IdDestination']['DestinationName1'])

            if not delivery_partner:
                raise EdiValidationError('Delivery Partner not found')

        _logger.debug("XML Order document valid")
        return True
Exemplo n.º 5
0
    def edi_import_vrd_validator(self, document_ids):
        edi_db = self.env['edi.tools.edi.document.incoming']
        document = edi_db.browse(document_ids)
        document.ensure_one()
        data = json.loads(document.content)[0]
        if data['state'] not in ['done', 'altered', 'cancelled']:
            raise EdiValidationError('No valid state found.')

        # Check if we can find the delivery
        delivery = self.search([('name', '=', data['name'])], limit=1)
        if not delivery:
            raise EdiValidationError(
                'Could not find the referenced delivery: {!s}.'.format(
                    content['name']))

        if delivery.state == 'done':
            raise EdiValidationError("Delivery already transfered.")

        return True
Exemplo n.º 6
0
    def edi_import_orders_d96a_validator(self, cr, uid, ids, context):
        _logger.info('StartValidatingD96A!!')
        edi_db = self.pool.get('edi.tools.edi.document.incoming')
        document = edi_db.browse(cr, uid, ids, context)

        try:
            data = json.loads(document.content)
            if not data:
                raise EdiValidationError('EDI Document is empty.')
        except Exception:
            raise EdiValidationError('Content is not valid JSON.')

        # Does this document have the correct root name?
        if not 'message' in data:
            raise EdiValidationError('Could not find field: message.')
        data = data['message']

        # Validate the document reference
        if not 'docnum' in data:
            raise EdiValidationError('Could not find field: docnum.')

        order_ids = self.search(cr, uid, [('client_order_ref', '=', data['docnum']), ('state', '!=', 'cancelled')])
        if order_ids:
            order = self.browse(cr, uid, order_ids)[0]
            raise EdiValidationError("Sales order %s exists for this reference" % (order.name,))

        # Validate the sender
        if not 'sender' in data:
            raise EdiValidationError('Could not find field: sender.')

        # Validate all the partners
        found_by = False
        found_dp = False
        found_iv = False
        if not 'partys' in data:
            raise EdiValidationError('Could not find field: partys.')
        try:
            data['partys'] = data['partys'][0]['party']
        except Exception:
            raise EdiValidationError('Erroneous structure for table: partys.')
        if len(data['partys']) == 0:
            raise EdiValidationError('Content of table partys is empty. ')

        partner_db = self.pool.get('res.partner')
        for party in data['partys']:
            if not 'qual' in party:
                raise EdiValidationError('Could not find field: qual (partner).')
            if not 'gln' in party:
                raise EdiValidationError('Could not find field: gln (partner).')
            pids = partner_db.search(cr, uid, [('ref', '=', party['gln'])])
            if not pids:
                raise EdiValidationError('Could not resolve partner {!s}.'.format(party['gln']))
            if party['qual'] == 'BY':
                found_by = True
            elif party['qual'] == 'DP':
                found_dp = True
        if not found_by or not found_dp:
            raise EdiValidationError('Couldnt find all required partners BY,DP.')

        # Validate all the line items
        if not 'lines' in data:
            raise EdiValidationError('Could not find field: lines.')
        try:
            data['lines'] = data['lines'][0]['line']
        except Exception:
            raise EdiValidationError('Erroneous structure for table: lines.')
        if len(data['lines']) == 0:
            raise EdiValidationError('Content of table lines is empty. ')

        product = self.pool.get('product.product')
        for line in data['lines']:
            if not 'ordqua' in line:
                raise EdiValidationError('Could not find field: ordqua (line).')
            if line['ordqua'] < 1:
                raise EdiValidationError('Ordqua (line) should be larger than 0.')
            if not 'gtin' in line:
                raise EdiValidationError('Could not find field: gtin (line).')
            pids = product.search(cr, uid, [('ean13', '=', line['gtin'])])
            if not pids:
                raise EdiValidationError('Could not resolve product {!s}.'.format(line['gtin']))

        # Validate timing information
        #if not 'deldtm' in data:
        #    raise EdiValidationError('Could not find field: deldtm.')
        #if not 'latedeltm' in data:
        #    raise EdiValidationError('Could not find field: latedeltm.')
        #if (not 'deldtm' in data) and (not 'latedeldtm' in data):
        #    raise EdiValidationError('Could not find field: deldtm or latedeldtm.')
        if not 'docdtm' in data:
            raise EdiValidationError('Could not find field: docdtm.')

        # If we get all the way to here, the document is valid
        _logger.info('validatedD96A!!')
        return True
Exemplo n.º 7
0
    def edi_import_order_xml(self, document):
        content = xmltodict.parse(document.content)
        header = content['InitialPurchaseOrder']['PurchaseOrderHeader']
        delivery_partner = self.env['res.partner'].search([
            ('name', '=', header['IdDestination']['DestinationName1'])
        ])
        _logger.info("Partner Found: %s", delivery_partner.id)

        param = {}

        param['partner_id'] = document.partner_id.id
        param['partner_shipping_id'] = delivery_partner.id
        param['partner_invoice_id'] = document.partner_id.id
        param['client_order_ref'] = header['IdOrderData'][
            'PurchaseOrderNumber'] + ' ' + header['IdOther']['Reference']

        if header['IdOther']['DeliveryDate'] != None:
            _logger.info("Requested Delivery Date Set")
            req_date = header['IdOther']['DeliveryDate'][6:] + '-' + header[
                'IdOther']['DeliveryDate'][3:5] + '-' + header['IdOther'][
                    'DeliveryDate'][:2] + ' 05:00:00'
            param['requested_date'] = req_date
        else:
            _logger.info("No Requested Delivery Date specified")

        param['order_line'] = []

        for line in content['InitialPurchaseOrder']['PurchaseOrderRows'][
                'IdRows']:
            if line == 'RowNumber':
                singleline = content['InitialPurchaseOrder'][
                    'PurchaseOrderRows']
                _logger.info("Single Line Detected, processing differently")
                break
            else:
                if 'BarCode' in line:
                    detail = {}
                    product = self.env['product.product'].search([
                        ('ean13', '=', line['BarCode'])
                    ]).id
                    if product:
                        detail['product_id'] = product
                        detail['product_uom_qty'] = float(line['Quantity'])
                        order_line = []
                        order_line.extend([0])
                        order_line.extend([False])
                        order_line.append(detail)
                        param['order_line'].append(order_line)
                        _logger.info("Product Found: %s", detail['product_id'])
                    else:
                        _logger.info("Product Not Found: %s", line['BarCode'])
                        raise EdiValidationError('Barcode not found: %s' %
                                                 line['BarCode'])

                else:
                    _logger.info("No BarCode element in line")

        #if singleline:
        #    if 'BarCode' in singleline:
        #        detail = {}
        #        detail['product_id'] =  self.env['product.product'].search([('ean13','=',singleline['BarCode'])]).id
        #        detail['product_uom_qty'] = float(line['Quantity'])
        #        order_line = []
        #        order_line.extend([0])
        #        order_line.extend([False])
        #        order_line.append(detail)
        #        param['order_line'].append(order_line)
        #        _logger.info("Single Product Found: %s", detail['product_id'])

        sid = self.create(param)
        so = self.browse(sid.id)[0]

        return so.name
Exemplo n.º 8
0
    def edi_import_actius_validator(self, document_ids):
        _logger.debug("Validating Actius document")

        # Read the EDI Document
        edi_db = self.env['edi.tools.edi.document.incoming']
        document = edi_db.browse(document_ids)
        document.ensure_one()

        # Convert the document to JSON
        try:
            content = xmltodict.parse(document.content)
            content = content['SHP_OBDLV_CONFIRM_DECENTRAL02']['IDOC'][
                'E1SHP_OBDLV_CONFIRM_DECENTR']
        except Exception:
            raise EdiValidationError(
                'Content is not valid XML or the structure deviates from what is expected.'
            )

        # Check if we can find the delivery
        delivery = self.search(
            [('name', '=', content['DELIVERY'].replace('_', '/'))], limit=1)
        if not delivery:
            raise EdiValidationError(
                'Could not find the referenced delivery: {!s}.'.format(
                    content['DELIVERY']))

        if delivery.state == 'done':
            raise EdiValidationError("Delivery already transfered.")

        if delivery.state == 'cancel':
            raise EdiValidationError("Delivery was manually cancelled.")

        lines_without_sequence = [
            ml for ml in delivery.move_lines if not ml.edi_sequence
        ]
        #if lines_without_sequence:
        #    raise EdiValidationError("Delivery %s has lines without edi_sequence" % (delivery.name))

        # Check if all the line items match
        if not content['E1BPOBDLVITEMCON']:
            raise EdiValidationError('No line items provided')

        # cast the line items to a list if there's only 1 item
        if not isinstance(content['E1BPOBDLVITEMCON'], list):
            content['E1BPOBDLVITEMCON'] = [content['E1BPOBDLVITEMCON']]
        for edi_line in content['E1BPOBDLVITEMCON']:
            if not edi_line['DELIV_ITEM']:
                raise EdiValidationError(
                    'Line item provided without an identifier.')
            if not edi_line['MATERIAL']:
                raise EdiValidationError(
                    'Line item provided without a material identifier.')
            if not edi_line['DLV_QTY_IMUNIT']:
                raise EdiValidationError(
                    'Line item provided without a quantity.')
            if float(edi_line['DLV_QTY_IMUNIT']) == 0.0:
                raise EdiValidationError(
                    'Line item provided with quantity equal to zero (0.0).')

            move_line = [
                x for x in delivery.move_lines
                if x.edi_sequence == edi_line['DELIV_ITEM']
            ]
            if not move_line:  # skip BOM explosion lines
                continue
            move_line = move_line[0]
            if move_line.product_id.name.upper() != edi_line['MATERIAL'].upper(
            ):
                raise EdiValidationError(
                    'Line mentioned with EDI sequence {!s} has a different material.'
                    .format(edi_line['DELIV_ITEM']))
            if move_line.location_id.id != move_line.reserved_quant_ids[
                    0].location_id.id:
                raise EdiValidationError(
                    'Location mismatch between source and quant reservation on line {!s}.'
                    .format(edi_line['DELIV_ITEM']))

        _logger.debug("Actius document valid")
        return True