Subversion Repositories SmartDukaan

Rev

Blame | Last modification | View Log | RSS feed

package com.smartdukaan.cron.migrations;

import com.spice.profitmandi.dao.entity.transaction.Order;
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
import com.spice.profitmandi.service.transaction.invoicing.InvoiceService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Re-files the e-invoice for an invoice NIC rejected (irn_generated = 0) once its data is corrected. The reset to
 * pending and the filing happen in one transaction: the scheduled IRN job only sees committed pending invoices, so it
 * cannot race this one, and a fresh process reads the corrected item master rather than a cached copy.
 */
@Component
public class IrnRetrier {

    private static final Logger LOGGER = LogManager.getLogger(IrnRetrier.class);

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private InvoiceService invoiceService;

    /** Returns the invoice's irn_generated afterwards; on any failure everything rolls back to how it was. */
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Throwable.class)
    public Boolean retry(String invoiceNumber) throws Exception {
        List<Order> orders = orderRepository.selectByInvoiceNumber(invoiceNumber);
        if (orders.isEmpty()) {
            throw new IllegalArgumentException("No orders for invoice " + invoiceNumber);
        }
        if (!Boolean.FALSE.equals(orders.get(0).isIrnGenerated())) {
            throw new IllegalStateException(invoiceNumber + " is not a rejected e-invoice (irn_generated="
                    + orders.get(0).isIrnGenerated() + ")");
        }
        for (Order order : orders) {
            order.setIrnGenerated(null);
        }
        invoiceService.saveInvoice(orders);
        Boolean result = orders.get(0).isIrnGenerated();
        if (!Boolean.TRUE.equals(result)) {
            throw new IllegalStateException(invoiceNumber + " still not filed (irn_generated=" + result + ")");
        }
        return result;
    }

    public void retryAll(List<String> invoiceNumbers) {
        for (String invoiceNumber : invoiceNumbers) {
            try {
                LOGGER.info("IRN RETRY {} : irn_generated={}", invoiceNumber, this.self().retry(invoiceNumber));
            } catch (Exception e) {
                LOGGER.error("IRN RETRY {} FAILED, left as it was - {}", invoiceNumber, e.getMessage(), e);
            }
        }
    }

    @Autowired
    private IrnRetrier self;

    private IrnRetrier self() {
        return self;
    }
}