'Given a data dict coming from ogone, verify it and find the related
transaction record. Create a payment token if an alias is returned.'

@api.model
def _ogone_form_get_tx_from_data(self, data):

    (reference, pay_id, shasign, alias) = (data.get('orderID'), data.get('PAYID'), data.get('SHASIGN'), data.get('ALIAS'))
    if ((not reference) or (not pay_id) or (not shasign)):
        error_msg = (_('Ogone:    received    data    with    missing    reference    (%s)    or    pay_id    (%s)    or    shasign    (%s)') % (reference, pay_id, shasign))
        _logger.info(error_msg)
        raise ValidationError(error_msg)
    tx = self.search([('reference', '=', reference)])
    if ((not tx) or (len(tx) > 1)):
        error_msg = (_('Ogone:    received    data    for    reference    %s') % reference)
        if (not tx):
            error_msg += _(';    no    order    found')
        else:
            error_msg += _(';    multiple    order    found')
        _logger.info(error_msg)
        raise ValidationError(error_msg)
    shasign_check = tx.acquirer_id._ogone_generate_shasign('out', data)
    if (shasign_check.upper() != shasign.upper()):
        error_msg = (_('Ogone:    invalid    shasign,    received    %s,    computed    %s,    for    data    %s') % (shasign, shasign_check, data))
        _logger.info(error_msg)
        raise ValidationError(error_msg)
    if (not tx.acquirer_reference):
        tx.acquirer_reference = pay_id
    if (alias and (tx.type == 'form_save')):
        Token = self.env['payment.token']
        domain = [('acquirer_ref', '=', alias)]
        cardholder = data.get('CN')
        if (not Token.search_count(domain)):
            _logger.info(('Ogone:    saving    alias    %s    for    partner    %s' % (data.get('CARDNO'), tx.partner_id)))
            ref = Token.create({'name': (data.get('CARDNO') + (('    -    ' + cardholder) if cardholder else '')), 'partner_id': tx.partner_id.id, 'acquirer_id': tx.acquirer_id.id, 'acquirer_ref': alias})
            tx.write({'payment_token_id': ref.id})
    return tx
