Subversion Repositories SmartDukaan

Rev

Blame | Last modification | View Log | RSS feed

package com.spice.profitmandi.service;

import com.spice.profitmandi.dao.entity.user.AgendaInstance;
import com.spice.profitmandi.dao.enumuration.dtr.AgendaSource;
import com.spice.profitmandi.dao.enumuration.dtr.AgendaType;
import com.spice.profitmandi.dao.repository.dtr.AgendaInstanceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * Per-store write step of the nightly agenda sync. Separate bean (not a method
 * on the orchestrator) so the REQUIRES_NEW proxy actually applies — one store's
 * failure rolls back only its own instance changes.
 *
 * Only AUTO instances are ever closed here; MANUAL instances belong to the
 * visiting team. OPEN on a type that already has any open instance (AUTO or
 * MANUAL) is a no-op via AgendaInstanceService.open.
 */
@Service
public class AgendaAutoRuleApplier {

    @Autowired
    AgendaInstanceRepository agendaInstanceRepository;

    @Autowired
    AgendaInstanceService agendaInstanceService;

    /** Returns {opened, closed} for this store. */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public int[] applyForStore(int fofoId, Map<AgendaType, AgendaRuleDecider.Decision> decisions)
            throws Exception {
        int opened = 0;
        int closed = 0;
        for (Map.Entry<AgendaType, AgendaRuleDecider.Decision> e : decisions.entrySet()) {
            AgendaType type = e.getKey();
            AgendaRuleDecider.Decision d = e.getValue();
            if (d.action == AgendaRuleDecider.Action.LEAVE) continue;

            AgendaInstance existing = agendaInstanceRepository.selectOpenByFofoIdAndType(fofoId, type.name());
            if (d.action == AgendaRuleDecider.Action.OPEN) {
                if (existing == null) {
                    agendaInstanceService.open(fofoId, type.name(), AgendaSource.AUTO, null, d.metric);
                    opened++;
                }
            } else { // CLOSE
                if (existing != null && AgendaSource.AUTO.name().equals(existing.getSource())) {
                    agendaInstanceService.closeByMetric(existing, d.metric);
                    closed++;
                }
            }
        }
        return new int[]{opened, closed};
    }
}