Subversion Repositories SmartDukaan

Rev

Blame | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.services;

import com.spice.profitmandi.common.web.client.RestClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Quality check for visit remarks, backed by the analyze service.
 *
 * POST /apis/analyze/v1/remarks/score
 *   {"remark":"...","asm_id":41292,"visit_id":"98213","agenda":"Credit dues","commit":true}
 * →  {"verdict":"good|bad","score":0.899,"authored_by_asm":true,
 *     "counts_toward_scorecard":true,"reasons":[{"code":"TOO_SHORT","detail":"..."}],
 *     "model_version":"...","visit_id":"98213"}
 *
 * commit=true tells the scorer to persist the score on its side, so pass it only
 * for a real checkout — probes should use false.
 */
@Service
public class RemarkScoreService {

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

    private static final String SCORE_URL = "https://team.smartdukaan.com/apis/analyze/v1/remarks/score";

    @Autowired
    private RestClient restClient;

    /**
     * Score one remark. Never throws and never returns null: a checkout is not
     * allowed to fail because the scorer is slow or down — the caller stores
     * whatever comes back, and an unreachable scorer is recorded as
     * {"error":"..."} so the gap is visible in remark_response instead of silent.
     */
    public JSONObject score(String remark, int asmId, String visitId, String agenda, boolean commit) {
        Map<String, Object> body = new LinkedHashMap<>();
        body.put("remark", remark);
        body.put("asm_id", asmId);
        body.put("visit_id", visitId);
        body.put("agenda", agenda != null ? agenda : "");
        body.put("commit", commit);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");

        try {
            String response = restClient.postJson(SCORE_URL, body, headers);
            JSONObject json = new JSONObject(response);
            if (!json.has("verdict")) {
                LOGGER.warn("Remark scorer returned no verdict for visitId={}: {}", visitId, response);
                return error("scorer returned no verdict");
            }
            return json;
        } catch (Exception e) {
            LOGGER.warn("Remark scoring failed for visitId={} agenda={}: {}", visitId, agenda, e.toString());
            return error(e.getClass().getSimpleName() + ": " + e.getMessage());
        }
    }

    private JSONObject error(String message) {
        return new JSONObject().put("error", message);
    }
}