Subversion Repositories SmartDukaan

Rev

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

package com.spice.profitmandi.dao.service;

import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.services.EmailService;
import com.spice.profitmandi.dao.entity.auth.AuthUser;
import com.spice.profitmandi.dao.entity.fofo.TrialForm;
import com.spice.profitmandi.dao.entity.user.Lead;
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
import com.spice.profitmandi.dao.enumuration.dtr.LeadStatus;
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
import com.spice.profitmandi.dao.repository.cs.CsService;
import com.spice.profitmandi.dao.repository.dtr.LeadRepository;
import com.spice.profitmandi.dao.service.loiForm.LoiFormServiceImpl;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class TrialServiceImpl implements TrialService {

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

    @Autowired
    JavaMailSender gmailRelaySender;

    @Autowired
    AuthRepository authRepository;

    @Autowired
    CsService csService;

    @Autowired
    EmailService emailService;

    @Autowired
    LeadRepository leadRepository;

    @Autowired
    private com.spice.profitmandi.dao.service.lead.LeadCreationService leadCreationService;

    @Override
    public void sentMailForTrialUser(TrialForm trialForm) throws Exception {
        String body =
                "Dear Team,<br><br>" +
                        "A new partner has registered via the SmartDukaan Partners App. Please review the details below and initiate the verification process immediately.<br><br>" +
                        "<strong>Applicant Name:</strong> " + trialForm.getFirstName() + " " + trialForm.getLastName() + "<br>" +
                        "<strong>Business Name:</strong> " + trialForm.getBusinessName() + "<br>" +
                        "<strong>Mobile:</strong> " + trialForm.getMobile() + "<br>" +
                        "<strong>Email:</strong> " + trialForm.getEmail() + "<br>" +
                        "<strong>GST Number:</strong> " + trialForm.getGstNumber() + "<br><br>" +
                        "<strong>Address:</strong><br>" +
                        trialForm.getAddressLine1() + "<br>" +
                        (trialForm.getAddressLine2() != null ? trialForm.getAddressLine2() + "<br>" : "") +
                        trialForm.getCity() + ", " + trialForm.getState() + " - " + trialForm.getPincode() + "<br><br>" +
                        "<strong>Date:</strong> " + LocalDate.now() + "<br>" +
                        "<strong>Required Actions:</strong><br>" +
                        " 1. Verify Details: Validate KYC documents and basic business information.<br>" +
                        " 2. Assess Potential: Check the location feasibility and estimated sales potential.<br>" +
                        " 3. Assign Territory: Assign the appropriate Area Sales Manager (ASM) and Business Manager (BM) in the system.<br><br>" +
                        "Regards,<br>SmartDukaan Team";

        String[] emailTo = {"kamini.sharma@smartdukaan.com", "rajat.bharadwaj@smartdukaan.com", "akhil.kumar@smartdukaan.com"};
        String[] cc = {"vaibhav.tandon@smartdukaan.com", "tarun.verma@smartdukaan.com"};
        LOGGER.info("RegistrationBody - " + body);
        emailService.sendMailWithAttachments(gmailRelaySender, emailTo, cc, "New Trial Registration: " + trialForm.getBusinessName(), body);


    }

    public void sentMailToTrialUser(TrialForm trialForm) throws Exception {

        String applicantName = trialForm.getFirstName() +
                (trialForm.getLastName() != null ? " " + trialForm.getLastName() : "");

        String body =
                "Hi " + applicantName + ",<br><br>" +
                        "We have successfully received your <strong>SmartDukaan registration application</strong>.<br><br>" +

                        "<strong>Current Status:</strong> <strong>Verification in Progress</strong><br><br>" +

                        "Your application is currently under review. Before activating your account, our team is verifying the " +
                        "documents you submitted, your business potential, and your location. Taaki onboarding bilkul smooth " +
                        "aur transparent ho.<br><br>" +

                        "<strong>What Happens Next?</strong><br>" +
                        "1. Our team will complete the verification process (approx. 2-3 days).<br>" +
                        "2. Once approved, you will receive your <strong>Login ID, Password,</strong> and onboarding details " +
                        "on your registered email address.<br>" +
                        "3. Simply log in using these details and start enjoying the <strong>SmartDukaan advantage</strong> immediately.<br><br>" +

                        "For any assistance, feel free to contact us:<br>" +
                        "<strong>Toll-Free:</strong> 1800-270-0273<br>" +
                        "<strong>Email:</strong> care@smartdukaan.com<br><br>" +

                        "Thank you for choosing <strong>SmartDukaan</strong>. We will connect with you shortly.<br><br>" +

                        "Regards,<br>" +
                        "Team SmartDukaan";


        String[] emailTo = {trialForm.getEmail()};
        String[] cc = {"sdtech@smartdukaan.com"}; // tarun.verma@smartdukaan.com
        LOGGER.info("RegistrationBody - " + body);
        emailService.sendMailWithAttachments(
                gmailRelaySender,
                emailTo,
                cc,
                "Application Received - Verification in Progress",
                body
        );
    }

    public void sentMailForTrialUserToSales(TrialForm trialForm) throws Exception {
        String body =
                "<strong>Sales Team Action:</strong><br>" +
                        "A new verified partner lead has been assigned to your territory. They have successfully passed the initial verification stage.<br><br>" +
                        "<strong>Lead Information:</strong><br>" +
                        "<strong>Applicant Name:</strong> " + trialForm.getFirstName() + " " + trialForm.getLastName() + "<br>" +
                        "<strong>Business Name:</strong> " + trialForm.getBusinessName() + "<br>" +
                        "<strong>Mobile:</strong> " + trialForm.getMobile() + "<br>" +
                        "<strong>Email:</strong> " + trialForm.getEmail() + "<br>" +
                        "<strong>GST Number:</strong> " + trialForm.getGstNumber() + "<br><br>" +
                        "<strong>Address:</strong><br>" +
                        trialForm.getAddressLine1() + "<br>" +
                        (trialForm.getAddressLine2() != null ? trialForm.getAddressLine2() + "<br>" : "") +
                        trialForm.getCity() + ", " + trialForm.getState() + " - " + trialForm.getPincode() + "<br><br>" +
                        "<strong>Strategic Objective:</strong> The partner has expressed initial interest. Your goal is to move them beyond trial onboarding.<br><br>" +
                        "<strong>Next Steps:</strong><br>" +
                        " 1. Contact Immediately: Call or visit the store within the next 24 hours.<br>" +
                        " 2. The Pitch: Explain the SmartDukaan ecosystem and pitch the Full Franchise Partner Model. Emphasize the long-term higher margins, income boost, brand access, tech support, and branding benefits over the trial version.<br>" +
                        " 3. Update Status: Log your interaction and the partner's interest level in the app immediately after the meeting.<br><br>" +
                        "Good Luck,<br>" +
                        "Regards,<br>SmartDukaan Team";

        List<AuthUser> salesAuthUserList = csService.getAuthUserIds(ProfitMandiConstants.TICKET_CATEGORY_SALES, Arrays.asList(EscalationType.L3, EscalationType.L4, EscalationType.L5));
        List<String> salesEmailList = new ArrayList<>();
        for (AuthUser authUser : salesAuthUserList) {
            if (authUser.getEmailId() != null && !authUser.getEmailId().trim().isEmpty()) {
                salesEmailList.add(authUser.getEmailId());
            }
        }
        AuthUser bmAuthUser = authRepository.selectById(trialForm.getBmId());
        AuthUser asmAuthUser = authRepository.selectById(trialForm.getAsmId());

        String[] emailTo = new String[]{bmAuthUser.getEmailId()};
        List<String> ccList = new ArrayList<>(salesEmailList);
        ccList.add(asmAuthUser.getEmailId());
        ccList.add("tarun.verma@smartdukaan.com");
        String[] cc = ccList.stream()
                .filter(email -> !email.trim().isEmpty())
                .toArray(String[]::new);
        LOGGER.info("RegistrationBody - " + body);
        LOGGER.info("cc list - " + Arrays.toString(cc));
        emailService.sendMailWithAttachments(gmailRelaySender, emailTo, cc, "NEW LEAD ASSIGNED: " + trialForm.getBusinessName() + "- Call/Visit ASAP", body);


    }

    public void sentMailForStoreCodeCreation(TrialForm trialForm) throws Exception {
        String body =
                "The trial user has been verified.<br><br>" +
                        "Please create Store Code for: <strong>" + trialForm.getBusinessName() + "</strong><br>" +
                        "Mobile Number: <strong>" + trialForm.getMobile() + "</strong><br><br>" +
                        "Regards,<br>SmartDukaan Team";

        String[] emailTo = {"gaurav.sharma@smartdukaan.com"};
        LOGGER.info("RegistrationBody - " + body);
        String[] cc = {"devkinandan.lal@smartdukaan.com", "tarun.verma@smartdukaan.com"};
        LOGGER.info("cc list - " + Arrays.toString(cc));
        emailService.sendMailWithAttachments(gmailRelaySender, emailTo, cc, "Store Code Creation Required for trial user" + trialForm.getBusinessName(), body);


    }

    public void sentRejectionMailToTrialUser(TrialForm trialForm) throws Exception {

        String applicantName = trialForm.getFirstName() +
                (trialForm.getLastName() != null ? " " + trialForm.getLastName() : "");

        String body =
                "Dear " + applicantName + ",<br><br>" +
                        "After a detailed review of your application, we regret to inform you that your " +
                        "<strong>30-Day Free Trial request</strong> cannot be approved based on the current " +
                        "eligibility criteria.<br><br>" +

                        "If you would like to understand the reason for this decision or discuss any concerns, " +
                        "please feel free to reach out to us at <strong>care@smartdukaan.com</strong> or call our " +
                        "Toll-Free number <strong>1800-270-0273</strong>.<br><br>" +

                        "Thank you for applying. We wish you continued success in your business journey. " +
                        "Aur agar future mein humari policies change hoti hain, hum aapse zaroor sampark karenge.<br><br>" +

                        "Regards,<br>" +
                        "Team SmartDukaan";


        String[] emailTo = {trialForm.getEmail()};
        String[] cc = {"sdtech@smartdukaan.com"};

        emailService.sendMailWithAttachments(
                gmailRelaySender,
                emailTo,
                cc,
                "Update on Your SmartDukaan Free Trial Request",
                body
        );
    }

    public void sendUpgradeRequestMail(TrialForm trialForm) throws Exception {

        String applicantName = trialForm.getFirstName() +
                (trialForm.getLastName() != null ? " " + trialForm.getLastName() : "");

        String body =
                "Dear " + applicantName + ",<br><br>" +
                        "Thank you for expressing your interest in the <strong>SmartDukaan Franchise Partner Program</strong>.<br><br>" +

                        "We have successfully received your request. Our team will connect with you shortly to discuss the " +
                        "requirements, eligibility, and the next steps. Taaki hum milkar ek strong aur long-term partnership " +
                        "build kar saken.<br><br>" +

                        "We look forward to taking this conversation forward.<br><br>" +

                        "Regards,<br>" +
                        "Team SmartDukaan";


        String[] emailTo = {trialForm.getEmail()};
        String[] cc = {"sdtech@smartdukaan.com"};

        emailService.sendMailWithAttachments(
                gmailRelaySender,
                emailTo,
                cc,
                "We’ve Received Your Interest in the SmartDukaan Franchise",
                body
        );
    }

    public void sendInternalFranchiseUpgradeMail(TrialForm trialForm) throws Exception {

        String applicantName = trialForm.getFirstName() +
                (trialForm.getLastName() != null ? " " + trialForm.getLastName() : "");

        String body =
                "Hi Team,<br><br>" +
                        "We have received a new interest request for the <strong>SmartDukaan Franchise Partner upgrade</strong> via the app.<br><br>" +

                        "<strong>Trial User Details:</strong><br>" +
                        "Name: " + applicantName + "<br>" +
                        "Business Name: " + trialForm.getBusinessName() + "<br>" +
                        "Registered Mobile: " + trialForm.getMobile() + "<br>" +
                        "User ID: " + trialForm.getId() + "<br>" +
                        "Request Date: " + trialForm.getUpdatedOn() + "<br><br>" +

                        "<strong>Action Required:</strong><br>" +
                        "Please review the user's profile and initiate the verification/onboarding process immediately.<br><br>" +

                        "Best,<br>" +
                        "SmartDukaan System";
        List<AuthUser> salesAuthUserList = csService.getAuthUserIds(ProfitMandiConstants.TICKET_CATEGORY_SALES, Arrays.asList(EscalationType.L3, EscalationType.L4, EscalationType.L5));
        List<String> salesEmailList = new ArrayList<>();
        for (AuthUser authUser : salesAuthUserList) {
            if (authUser.getEmailId() != null && !authUser.getEmailId().trim().isEmpty()) {
                salesEmailList.add(authUser.getEmailId());
            }
        }
        AuthUser bmAuthUser = authRepository.selectById(trialForm.getBmId());
        AuthUser asmAuthUser = authRepository.selectById(trialForm.getAsmId());

        String[] emailTo = new String[]{bmAuthUser.getEmailId()};
        List<String> ccList = new ArrayList<>(salesEmailList);
        ccList.add(asmAuthUser.getEmailId());
        ccList.add("tarun.verma@smartdukaan.com");
        String[] cc = ccList.stream()
                .filter(email -> !email.trim().isEmpty())
                .toArray(String[]::new);
        emailService.sendMailWithAttachments(
                gmailRelaySender,
                emailTo,
                cc,
                "Franchise Upgrade Request - " + applicantName + ", " + trialForm.getBusinessName(),
                body
        );
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void createLeadAndNotifyBgcForTrial(TrialForm trialForm) {
        // REQUIRES_NEW: this add-on runs in an isolated transaction. If the Lead
        // persist or the BGC mail fails, the outer trial-registration transaction
        // is completely unaffected — no rollback, no session poisoning.
        // Step 1 — persist a Lead in lead management. Failure is logged but never
        // rolls back the trial registration (called after trialForm is already saved).
        try {
            Lead existing = null; // no dedup by mobile — a single trial can generate its own lead row
            Lead lead = new Lead();
            lead.setFirstName(trialForm.getFirstName() != null ? trialForm.getFirstName() : "");
            lead.setLastName(trialForm.getLastName() != null ? trialForm.getLastName() : "");
            lead.setLeadMobile(trialForm.getMobile());
            lead.setOutLetName(trialForm.getBusinessName() != null ? trialForm.getBusinessName() : "");
            lead.setCity(trialForm.getCity() != null ? trialForm.getCity() : "");
            lead.setState(trialForm.getState() != null ? trialForm.getState() : "");
            String addr = (trialForm.getAddressLine1() != null ? trialForm.getAddressLine1() : "")
                    + (trialForm.getAddressLine2() != null && !trialForm.getAddressLine2().isEmpty()
                    ? ", " + trialForm.getAddressLine2() : "");
            lead.setAddress(addr);
            lead.setSource("Trial Registration");
            lead.setStatus(LeadStatus.pending);
            lead.setColor("yellow");
            lead.setCreatedBy("system");
            lead.setCreatedTimestamp(LocalDateTime.now());
            lead.setUpdatedTimestamp(LocalDateTime.now());
            // Unattended: a trial signup has no agent to offer an override to. A collision is
            // skipped and mailed to the Call Center desk rather than creating a second live lead.
            leadCreationService.createUnattended(lead);
            LOGGER.info("Trial-to-Lead created: leadId={} for trialMobile={}", lead.getId(), trialForm.getMobile());
        } catch (Exception e) {
            LOGGER.error("Failed to create Lead from Trial for mobile=" + trialForm.getMobile(), e);
        }

        // Step 2 — email BGC L2 + L3 with tarun.verma + kamini.sharma in CC.
        try {
            List<AuthUser> bgcUsers = csService.getAuthUserIds(
                    ProfitMandiConstants.TICKET_CATEGORY_BGC,
                    Arrays.asList(EscalationType.L2, EscalationType.L3));
            List<String> bgcEmails = new ArrayList<>();
            for (AuthUser u : bgcUsers) {
                if (u.getEmailId() != null && !u.getEmailId().trim().isEmpty()) {
                    bgcEmails.add(u.getEmailId());
                }
            }
            if (bgcEmails.isEmpty()) {
                LOGGER.warn("No BGC L2/L3 users found for trial mobile={} — skipping BGC mail", trialForm.getMobile());
                return;
            }
            String[] emailTo = bgcEmails.toArray(new String[0]);
            String[] cc = new String[]{"tarun.verma@smartdukaan.com", "kamini.sharma@smartdukaan.com"};

            String applicantName = trialForm.getFirstName()
                    + (trialForm.getLastName() != null ? " " + trialForm.getLastName() : "");
            String body =
                    "Dear BGC Team,<br><br>" +
                            "A new lead has been generated from a trial registration. Please initiate the background check process.<br><br>" +
                            "<strong>Applicant Name:</strong> " + applicantName + "<br>" +
                            "<strong>Business Name:</strong> " + (trialForm.getBusinessName() != null ? trialForm.getBusinessName() : "-") + "<br>" +
                            "<strong>Mobile:</strong> " + trialForm.getMobile() + "<br>" +
                            "<strong>Email:</strong> " + (trialForm.getEmail() != null ? trialForm.getEmail() : "-") + "<br>" +
                            "<strong>GST Number:</strong> " + (trialForm.getGstNumber() != null ? trialForm.getGstNumber() : "-") + "<br><br>" +
                            "<strong>Address:</strong><br>" +
                            (trialForm.getAddressLine1() != null ? trialForm.getAddressLine1() + "<br>" : "") +
                            (trialForm.getAddressLine2() != null && !trialForm.getAddressLine2().isEmpty() ? trialForm.getAddressLine2() + "<br>" : "") +
                            (trialForm.getCity() != null ? trialForm.getCity() : "-") + ", "
                            + (trialForm.getState() != null ? trialForm.getState() : "-") + " - "
                            + (trialForm.getPincode() != null ? trialForm.getPincode() : "-") + "<br><br>" +
                            "<strong>Source:</strong> Trial Registration<br><br>" +
                            "Please review and initiate the BGC verification at the earliest.<br><br>" +
                            "Regards,<br>SmartDukaan Team";

            emailService.sendMailWithAttachments(gmailRelaySender, emailTo, cc,
                    "New Lead for BGC - " + (trialForm.getBusinessName() != null ? trialForm.getBusinessName() : applicantName),
                    body);
            LOGGER.info("BGC L2/L3 lead-notification mail sent for trial mobile={} to={} cc={}",
                    trialForm.getMobile(), Arrays.toString(emailTo), Arrays.toString(cc));
        } catch (Exception e) {
            LOGGER.error("Failed to send BGC L2/L3 mail for trial mobile=" + trialForm.getMobile(), e);
        }
    }

}