Follows the usual ad-server flow (serve -> impression -> click):
- GET /api/ads/next returns an impressionToken: HMAC-signed (ads.tracking.secret,
defaults to jwt.secret) ad id, campaign id, subject and nonce, valid 1 hour.
/impression and /click accept it, verify the signature, count each nonce once
(Redis SET NX) and take the user/session from the token, so impressions
cannot be forged or replayed. Requests without a token keep working until
ads.tracking.require-token is switched on after the frontend update.
- The frequency cap is per campaign and calendar day (ads.timezone) and grows
on real impressions, not on serving: ad:cap:<subject>:<campaign>:<yyyyMMdd>.
- Selection reads a 30-second in-memory snapshot of eligible ads (projection,
invalidated locally on admin changes), filters capped campaigns with one
MGET, picks by weight and then sets the cooldown atomically. The weighted
sort drew random numbers inside the comparator, breaking its contract.
- Campaigns past endDate are finished every 10 minutes (ShedLock).
- GET /api/v1/admin/campaigns/{id}/stats: impressions, clicks and CTR per ad
for a date range; composite indexes on impression/click (changelog 021).
- Removed unused cascade collections on Campaign/Advertising, the unused
FullscreenAdActivateRequestDto and the /api/ads/impression/beacon rule.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
122 lines
4.5 KiB
Java
122 lines
4.5 KiB
Java
package com.krylov.refound.service.advertising;
|
||
|
||
import com.krylov.refound.dto.advertising.CampaignCreateRequestDto;
|
||
import com.krylov.refound.dto.advertising.CampaignResponseDto;
|
||
import com.krylov.refound.dto.advertising.CampaignStatusUpdateRequestDto;
|
||
import com.krylov.refound.dto.advertising.CampaignUpdateRequestDto;
|
||
import com.krylov.refound.entity.advertising.Campaign;
|
||
import com.krylov.refound.enums.advertising.CampaignStatus;
|
||
import com.krylov.refound.exception.InvalidCampaignStatusTransitionException;
|
||
import com.krylov.refound.repository.advertising.CampaignRepository;
|
||
import jakarta.persistence.EntityNotFoundException;
|
||
import java.util.List;
|
||
import java.util.Optional;
|
||
import lombok.RequiredArgsConstructor;
|
||
import lombok.extern.slf4j.Slf4j;
|
||
import org.springframework.stereotype.Service;
|
||
import org.springframework.transaction.annotation.Transactional;
|
||
|
||
@Slf4j
|
||
@Service
|
||
@RequiredArgsConstructor
|
||
public class CampaignService {
|
||
|
||
private final CampaignRepository campaignRepository;
|
||
private final AdvertisingSelectionService selectionService;
|
||
|
||
@Transactional(readOnly = true)
|
||
public List<CampaignResponseDto> getCampaign() {
|
||
return campaignRepository.findAllByOrderByCreatedAtDesc()
|
||
.stream()
|
||
.map(this::toDto)
|
||
.toList();
|
||
}
|
||
|
||
public Optional<CampaignResponseDto> getCampaignById(Long campaignId) {
|
||
return campaignRepository.findById(campaignId).map(this::toDto);
|
||
}
|
||
|
||
@Transactional
|
||
public CampaignResponseDto createCampaign(CampaignCreateRequestDto request){
|
||
Campaign campaign = new Campaign();
|
||
campaign.setName(request.name());
|
||
campaign.setStatus(CampaignStatus.DRAFT);
|
||
campaign.setStartDate(request.startDate());
|
||
campaign.setEndDate(request.endDate());
|
||
campaign.setDailyImpressionCap(request.dailyImpressionCap());
|
||
campaignRepository.save(campaign);
|
||
log.info("campaign {} created", campaign);
|
||
return toDto(campaign);
|
||
}
|
||
|
||
@Transactional
|
||
public CampaignResponseDto updateCampaign(Long campaignId, CampaignUpdateRequestDto request) {
|
||
Campaign campaign = campaignRepository.findById(campaignId)
|
||
.orElseThrow(() -> new EntityNotFoundException("Campaign not found: " + campaignId));
|
||
|
||
if (!request.startDate().isBefore(request.endDate())) {
|
||
throw new IllegalArgumentException("startDate must be before endDate");
|
||
}
|
||
if (request.dailyImpressionCap() <= 0) {
|
||
throw new IllegalArgumentException("dailyImpressionCap must be positive");
|
||
}
|
||
|
||
campaign.setName(request.name());
|
||
campaign.setStartDate(request.startDate());
|
||
campaign.setEndDate(request.endDate());
|
||
campaign.setDailyImpressionCap(request.dailyImpressionCap());
|
||
|
||
log.info("campaign {} updated", campaignId);
|
||
selectionService.invalidateCache();
|
||
return toDto(campaign);
|
||
}
|
||
|
||
@Transactional
|
||
public CampaignResponseDto updateCampaignStatus(Long campaignId, CampaignStatusUpdateRequestDto request) {
|
||
Campaign campaign = campaignRepository.findById(campaignId)
|
||
.orElseThrow(() -> new EntityNotFoundException("Campaign not found: " + campaignId));
|
||
|
||
if (!isValidTransition(campaign.getStatus(), request.status())) {
|
||
throw new InvalidCampaignStatusTransitionException(
|
||
"Invalid status transition: "
|
||
+ campaign.getStatus()
|
||
+ " -> "
|
||
+ request.status()
|
||
);
|
||
}
|
||
|
||
// Раньше статус менялся bulk-UPDATE'ом, а ответ собирался из сущности
|
||
// со старым статусом — фронт видел прежнее значение
|
||
campaign.setStatus(request.status());
|
||
selectionService.invalidateCache();
|
||
return toDto(campaign);
|
||
}
|
||
|
||
/**
|
||
* Разрешённые переходы статуса кампании. Не даёт, например, воскресить
|
||
* FINISHED обратно в ACTIVE или перепрыгнуть из DRAFT сразу в FINISHED.
|
||
*/
|
||
private boolean isValidTransition(CampaignStatus from, CampaignStatus to) {
|
||
if (from == to) {
|
||
return false;
|
||
}
|
||
return switch (from) {
|
||
case DRAFT -> to == CampaignStatus.ACTIVE;
|
||
case ACTIVE -> to == CampaignStatus.PAUSED || to == CampaignStatus.FINISHED;
|
||
case PAUSED -> to == CampaignStatus.ACTIVE || to == CampaignStatus.FINISHED;
|
||
case FINISHED -> false;
|
||
};
|
||
}
|
||
|
||
private CampaignResponseDto toDto(Campaign campaign) {
|
||
return new CampaignResponseDto(
|
||
campaign.getId(),
|
||
campaign.getName(),
|
||
campaign.getStatus(),
|
||
campaign.getStartDate(),
|
||
campaign.getEndDate(),
|
||
campaign.getDailyImpressionCap());
|
||
}
|
||
|
||
}
|