# SyncM3AccountTask.java

    package cloud.wconnect.finance.businesstask.pl;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.m3Config.PropertyM3ConfigDTO;
    import cloud.wconnect.commonlib.pojo.dto.m3Config.TenantM3ConfigDTO;
    import cloud.wconnect.commonlib.pojo.query.OpenFunctionPropertyQuery;
    import cloud.wconnect.commonlib.service.M3ConfigInternalService;
    import cloud.wconnect.commonlib.service.MailInternalService;
    import cloud.wconnect.commonlib.service.PropertyInternalService;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.finance.service.pl.IM3AccountService;
    import com.google.common.collect.Lists;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.CollectionUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;

    import java.text.MessageFormat;
    import java.util.List;
    import java.util.concurrent.TimeUnit;

    /**
     * 每天凌晨4点调用M3接口获取指定资产的Account数据
     *
     * @author lichen
     * @date 2025/9/25
     */
    @Slf4j
    @Component
    public class SyncM3AccountTask {

        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        @Value("${default.timezone}")
        private String defaultTimezone;
        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private PropertyInternalService propertyInternalService;
        @Autowired
        private IM3AccountService m3AccountService;
        @Autowired
        private M3ConfigInternalService m3ConfigInternalService;
        //并发前缀
        private static final String PREFIX_KEY = "wconnect:task:pl:sync-m3-account:";

        /**
         * 每天凌晨4点调用M3接口获取指定资产的Account数据
         *
         * @return void
         * @author lichen
         * @date 2025/9/25
         */
        @Scheduled(cron = "${schedule.cron.pl.sync-m3-account}", zone = "${default.timezone}")
        public void syncM3Account() {
            try {
                String currentDateStr = DateTimeUtils.dateNowStr(defaultTimezone, BaseConstant.DATE_FORMAT_YYMMDDHH);
                if (!preventConcurrency(PREFIX_KEY + currentDateStr)) {
                    return;
                }
                //查询开通P&L功能的有效资产
                List<PropertyDTO> openFunctionPropertyDTOList = propertyInternalService.getOpenFunctionProperty(OpenFunctionPropertyQuery.builder()
                                .openFunctionIds(Lists.newArrayList(FunctionIdConstant.PL)).build())
                        .stream().filter(PropertyDTO::getStatus).toList();
                if (CollectionUtils.isEmpty(openFunctionPropertyDTOList)) {
                    log.info("syncM3Account.syncM3Account, no open function property");
                    return;
                }
                List<Integer> propertyIds = openFunctionPropertyDTOList.stream().map(PropertyDTO::getId).toList();

                //获取资产的M3配置
                List<TenantM3ConfigDTO> tenantM3ConfigDTOS = m3ConfigInternalService.listPropertyM3Config(propertyIds);
                if (CollectionUtils.isEmpty(tenantM3ConfigDTOS)) {
                    log.info("syncM3Account.syncM3Account, no m3 config");
                    return;
                }

                for (TenantM3ConfigDTO tenantM3ConfigDTO : tenantM3ConfigDTOS) {
                    List<PropertyM3ConfigDTO> propertyM3ConfigDTOS = tenantM3ConfigDTO.getPropertyM3ConfigDTOS();
                    if (CollectionUtils.isEmpty(propertyM3ConfigDTOS)) {
                        log.info("syncM3Account.syncM3Account, no property m3 config, tenantId:" + tenantM3ConfigDTO.getTenantId());
                        continue;
                    }

                    for (PropertyM3ConfigDTO propertyM3ConfigDTO : propertyM3ConfigDTOS) {
                        //同步资产的M3 Account数据
                        doSyncPropertyM3Account(tenantM3ConfigDTO, propertyM3ConfigDTO);
                    }
                }
            } catch (Exception e) {
                String alertTitle = "[Warning] - P&L Exceptions about synchronize m3 acccount";
                //发送预警邮件
                mailInternalService.sendAlertEmail(alertTitle,
                        "<p>There is something wrong when sync m3 acccount.</p>"
                                + "<p>Exception:" + e + "</p>"
                );
            }
        }

        /**
         * 同步资产M3 Account数据，失败后重试3次
         *
         * @param tenantM3ConfigDTO   租户的M3配置信息
         * @param propertyM3ConfigDTO 资产的M3配置信息
         * @return void
         * @author lichen
         * @date 2025/9/26
         */
        private void doSyncPropertyM3Account(TenantM3ConfigDTO tenantM3ConfigDTO, PropertyM3ConfigDTO propertyM3ConfigDTO) {
            try {
                m3AccountService.syncPropertyM3Account(tenantM3ConfigDTO, propertyM3ConfigDTO);
            } catch (Exception exception) {
                String alertTitle = "[Warning] - P&L Exceptions about synchronize the specified property with the M3 Account";
                String content = MessageFormat.format("<p>There is something wrong when sync m3 acccount, tenantId:{0}, propertyId:{1}</p><p>Exception:{2}</p>",
                        tenantM3ConfigDTO.getTenantId(), propertyM3ConfigDTO.getPropertyId(), exception);
                //发送预警邮件
                mailInternalService.sendAlertEmail(alertTitle, content);
            }
        }

        /**
         * 阻止并发操作
         *
         * @param key 缓存key
         * @return java.lang.Boolean
         * @author lichen
         * @date 2023/10/16
         */
        private Boolean preventConcurrency(String key) {
            return redisTemplate.opsForValue().setIfAbsent(key, 0, 1, TimeUnit.DAYS);
        }

    }