Subversion Repositories SmartDukaan

Rev

Rev 36347 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.service.offers;

import com.spice.profitmandi.dao.entity.transaction.CronBatch;
import com.spice.profitmandi.dao.enumuration.catalog.OfferSchemeType;
import com.spice.profitmandi.dao.model.CreateOfferRequest;
import com.spice.profitmandi.service.cron.CronBatchService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * Orchestrates offer processing with per-partner transaction isolation and batch tracking.
 *
 * NO @Transactional on this class or any of its methods — the orchestrator must not
 * carry an outer transaction. Each partner's write work runs in REQUIRES_NEW via
 * OfferProcessingHelper; batch metadata writes run in REQUIRES_NEW via CronBatchService.
 * If the caller is already inside a transaction (e.g., controller class-level @Transactional),
 * REQUIRES_NEW will suspend it cleanly.
 */
@Service
public class OfferBatchService {

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

    @Autowired
    private OfferService offerService;

    @Autowired
    private OfferProcessingHelper offerProcessingHelper;

    @Autowired
    private CronBatchService cronBatchService;

    public void processOfferWithBatch(int offerId) throws Exception {
        CreateOfferRequest createOfferRequest = offerProcessingHelper.loadOfferRequest(offerId);
        if (createOfferRequest == null) {
            return;
        }
        LOGGER.info("Processing offer {} (type={}) with batch tracking", offerId, createOfferRequest.getSchemeType());

        if (createOfferRequest.getSchemeType().equals(OfferSchemeType.ACTIVATION)) {
            processActivationOfferWithBatch(offerId, createOfferRequest);
        } else if (createOfferRequest.getSchemeType().equals(OfferSchemeType.SELLIN)) {
            processSellinOfferWithBatch(offerId, createOfferRequest);
        } else {
            LOGGER.warn("Offer {} has unsupported scheme type: {}", offerId, createOfferRequest.getSchemeType());
        }
    }

    private void processActivationOfferWithBatch(int offerId, CreateOfferRequest createOfferRequest) throws Exception {
        List<OfferPartnerPayoutData> partnerPayouts;
        try {
            partnerPayouts = offerService.calculateOfferPayouts(createOfferRequest);
        } catch (Exception e) {
            LOGGER.error("Failed to calculate activation payouts for offer {}: {}", offerId, e.getMessage());
            return;
        }

        if (partnerPayouts.isEmpty()) {
            LOGGER.info("No eligible partners for activation offer {}", offerId);
            return;
        }

        LinkedHashMap<Integer, String> fofoIdPartnerNameMap = new LinkedHashMap<>();
        for (OfferPartnerPayoutData data : partnerPayouts) {
            fofoIdPartnerNameMap.put(data.getFofoId(), "fofo-" + data.getFofoId());
        }

        CronBatch batch = cronBatchService.createBatch("processActivationOffer-" + offerId, fofoIdPartnerNameMap);

        for (OfferPartnerPayoutData data : partnerPayouts) {
            try {
                offerProcessingHelper.processPartnerOfferPayout(
                        batch.getId(), data.getFofoId(), offerId, createOfferRequest.getDescription(),
                        data.getLineItemValueMap(), data.getItemCriteriaPayout(), data.getCriteriaId(),
                        data.getSerialNumberPaid(), data.getAgeingSummaryModelsMap(),
                        data.getEligiblePayoutValue(), data.isDiscount());
            } catch (Exception e) {
                LOGGER.error("Activation offer {} failed for fofoId={}: {}", offerId, data.getFofoId(), e.getMessage());
                cronBatchService.markItemFailed(batch.getId(), data.getFofoId(), e.getMessage());
            }
        }

        cronBatchService.finalizeBatch(batch.getId());
    }

    private void processSellinOfferWithBatch(int offerId, CreateOfferRequest createOfferRequest) throws Exception {
        List<SellinPartnerPayoutData> partnerPayouts;
        try {
            partnerPayouts = offerService.calculateSellinPayouts(createOfferRequest);
        } catch (Exception e) {
            LOGGER.error("Failed to calculate sellin payouts for offer {}: {}", offerId, e.getMessage());
            return;
        }

        if (partnerPayouts.isEmpty()) {
            LOGGER.info("No eligible partners for sellin offer {}", offerId);
            return;
        }

        LinkedHashMap<Integer, String> fofoIdPartnerNameMap = new LinkedHashMap<>();
        for (SellinPartnerPayoutData data : partnerPayouts) {
            fofoIdPartnerNameMap.put(data.getFofoId(), "fofo-" + data.getFofoId());
        }

        CronBatch batch = cronBatchService.createBatch("processSellinOffer-" + offerId, fofoIdPartnerNameMap);

        for (SellinPartnerPayoutData data : partnerPayouts) {
            try {
                offerProcessingHelper.processPartnerSellinPayout(
                        batch.getId(), data.getFofoId(), offerId, createOfferRequest.getDescription(),
                        data.getSerialNumberInventoryItemMap(), data.getItemCriteriaPayout(), data.getCriteriaId(),
                        data.getSerialNumberPaid(), data.getEligiblePayoutValue(), data.isDiscount());
            } catch (Exception e) {
                LOGGER.error("Sellin offer {} failed for fofoId={}: {}", offerId, data.getFofoId(), e.getMessage());
                cronBatchService.markItemFailed(batch.getId(), data.getFofoId(), e.getMessage());
            }
        }

        cronBatchService.finalizeBatch(batch.getId());
    }
}