-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCampaignService.php
More file actions
405 lines (352 loc) · 19.2 KB
/
CampaignService.php
File metadata and controls
405 lines (352 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
<?php
namespace MatchBot\Domain;
use Assert\InvalidArgumentException;
use Assert\LazyAssertionException;
use MatchBot\Application\Assertion;
use MatchBot\Application\HttpModels\Campaign as CampaignHttpModel;
use MatchBot\Application\HttpModels\MetaCampaign as MetaCampaignHttpModel;
use MatchBot\Client\Campaign as CampaignClient;
use MatchBot\Domain\Campaign as CampaignDomainModel;
use Psr\Log\LoggerInterface;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
/**
* @psalm-import-type SFCampaignApiResponse from CampaignClient
*/
class CampaignService
{
private const string METACAMPAIGN_MATCH_AMOUNT_REMAINING_PREFIX = 'metacampaign_match_amount_remaining.';
private const string METACAMPAIGN_MATCH_AMOUNT_RAISED_PREFIX = 'metacampaign_match_amount_raised.';
private const string METACAMPAIGN_MATCH_FUNDS_TOTAL_PREFIX = 'metacampaign_match_funds_total.';
public function __construct(
private CampaignRepository $campaignRepository,
private MetaCampaignRepository $metaCampaignRepository,
private CacheInterface $cache,
private DonationRepository $donationRepository,
private MatchFundsService $matchFundsService,
private LoggerInterface $log,
private ClockInterface $clock,
) {
}
/**
* Gets the most relevant target, factoring in meta-campaign in shared funds scenarios and using MatchBot's own
* funding records.
*
* The non-shared, matched charity campaign case should derive a sum (on the final line) which matches
* the Salesforce-reported totalFundraisingTarget. {@see getTotalFundraisingTarget()} which surfaces that
* directly for sorting etc.
*/
public function campaignTarget(Campaign $campaign, ?MetaCampaign $metaCampaign): Money
{
if ($metaCampaign) {
Assertion::eq($campaign->getMetaCampaignSlug(), $metaCampaign->getSlug());
}
if ($metaCampaign && $metaCampaign->isEmergencyIMF()) {
// Emergency IMF targets can currently assume a shared match pot, so use parent totals to calculate
// target for Emergency IMFs' children: double the total match funds available (or override if set)
//because parents do not have total fund raising target set */
return $this->cachedMetaCampaignMatchFundsTotal($metaCampaign)->times(2);
}
// SF implementation uses `Type__c = 'Regular Campaign'` is the condition. We don't have a copy of
// `Type__c` but I think the below is equivalent:
if (!$campaign->isMatched()) {
return $campaign->getTotalFundraisingTarget();
}
return $campaign->getStatistics()->getMatchFundsTotal()->times(2);
}
/**
* @return array<string, mixed>
*/
public function renderCampaignSummary(CampaignDomainModel $campaign): array
{
$sfCampaignData = $campaign->getSalesforceData();
$stats = $campaign->getStatistics();
$slug = $campaign->getMetaCampaignSlug();
$metaCampaign = $slug ? $this->metaCampaignRepository->getBySlug($slug) : null;
return [
'charity' => [
'id' => $campaign->getCharity()->getSalesforceId(),
'name' => $campaign->getCharity()->getName(),
],
'isRegularGiving' => $campaign->isRegularGiving(),
'id' => $campaign->getSalesforceId(),
'amountRaised' => $stats->getAmountRaised()->toMajorUnitFloat(),
'currencyCode' => $campaign->getCurrencyCode(),
'endDate' => $this->formatDate($campaign->getEndDate()),
'isMatched' => $campaign->isMatched(),
'matchFundsRemaining' => $stats->getMatchFundsRemaining()->toMajorUnitFloat(),
'startDate' => $this->formatDate($campaign->getStartDate()),
'status' => $campaign->getStatus(),
'title' => $campaign->getCampaignName(),
// fields below are all directly entered through the SF UI and not involved in business logic, so no need to
// do anything more than this with them in matchbot for now.
'beneficiaries' => $sfCampaignData['beneficiaries'],
'categories' => $sfCampaignData['categories'],
'championName' => $sfCampaignData['championName'],
'imageUri' => $sfCampaignData['bannerUri'],
'target' => $sfCampaignData['target'],
'parentUsesSharedFunds' => $metaCampaign && $metaCampaign->usesSharedFunds(),
'parentRef' => $metaCampaign?->getSlug()->slug,
// FE model also currently has a key-optional 'percentRaised' field, but SF never sends it and nothing in FE
// runtime touches it - SF is currently doing its own division to calculate percent raised in
// percentRaisedOfIndividualCampaign. We don't need to send it here but could start sending it in future.
];
}
public function renderMetaCampaign(MetaCampaign $metaCampaign): MetaCampaignHttpModel
{
$salesforceId = $metaCampaign->getSalesforceId();
Assertion::notNull($salesforceId);
$bannerLayout = MetaCampaignLayoutChoices::forSlug($metaCampaign);
$bannerUri = $bannerLayout->imageUri ?? $metaCampaign->getBannerUri();
return new MetaCampaignHttpModel(
id: $salesforceId,
title: $metaCampaign->getTitle(),
currencyCode: $metaCampaign->getCurrency()->isoCode(case: 'upper'),
status: $metaCampaign->getStatusAt($this->clock->now()),
hidden: $metaCampaign->isHidden(),
ready: true, // @todo-mat-405 - store get a copy of the `ready` value for the metacampaign from SF.
summary: $metaCampaign->getSummary(),
bannerUri: $bannerUri?->__toString(),
amountRaised: $this->getAmountRaisedForMetaCampaign($metaCampaign)->toMajorUnitFloat(),
matchFundsRemaining: $this->cachedMetaCampaignMatchFundsRemaining($metaCampaign)->toMajorUnitFloat(),
donationCount: $this->metaCampaignRepository->countCompleteDonationsToMetaCampaign($metaCampaign),
startDate: $this->formatDate($metaCampaign->getStartDate()),
endDate: $this->formatDate($metaCampaign->getEndDate()),
matchFundsTotal: $this->cachedMetaCampaignMatchFundsTotal($metaCampaign)->toMajorUnitFloat(),
campaignCount: $this->campaignRepository->countCampaignsInMetaCampaign($metaCampaign),
usesSharedFunds: $metaCampaign->usesSharedFunds(),
shouldBeIndexed: $metaCampaign->shouldBeIndexed($this->clock->now()),
useDon1120Banner: ! \is_null($bannerLayout),
bannerLayout: $bannerLayout,
);
}
/**
* Converts an instance matchbot's internal campaign model to an HTTP model for use in front end.
*
* May need to use some additional data from outside the campaign at least if available. In the short term
* we may need to call out to SF to get the most current data as required for some fields, e.g. amountRaised,
* although if SF is not available or doesn't know this campaign we could fall back to a null or default value
* perhaps.
*
* @return array<string, mixed> Campaign as associative array ready to render as JSON and send to FE
*/
public function renderCampaign(CampaignDomainModel $campaign, ?MetaCampaign $metaCampaign): array
{
$charity = $campaign->getCharity();
$campaignStatus = $campaign->getStatus();
Assertion::inArray($campaignStatus, ['Active','Expired','Preview', null]);
// the next two vars are the data as originally served to matchbot by Salesforce. For now we
// repeat many parts of them verbatim, but its likely we may want to replace several fields with things
// either computed inside matchbot or saved to specific fields in our own object model soon, so that we can
// show more up-to-date results and also ensure that what we're presenting matches with data used for
// matchbot business logic.
$sfCampaignData = $campaign->getSalesforceData();
$sfCharityData = $sfCampaignData['charity'];
Assertion::notNull($sfCharityData, 'Charity data should not be null for a charity campaign');
try {
$websiteUri = $charity->getWebsiteUri()?->__toString();
} catch (\Laminas\Diactoros\Exception\InvalidArgumentException) {
$this->log->warning("Bad website URI for charity {$charity->getSalesforceId()} for campaign {$campaign->getSalesforceId()}");
$websiteUri = null;
}
$charityHttpModel = new \MatchBot\Application\HttpModels\Charity(
id: $charity->getSalesforceId(),
name: $charity->getName(),
optInStatement: $sfCharityData['optInStatement'],
facebook: $sfCharityData['facebook'],
giftAidOnboardingStatus: $sfCharityData['giftAidOnboardingStatus'],
hmrcReferenceNumber: $charity->getHmrcReferenceNumber(),
instagram: $sfCharityData['instagram'],
linkedin: $sfCharityData['linkedin'],
twitter: $sfCharityData['twitter'],
website: $websiteUri,
phoneNumber: $charity->getPhoneNumber(),
emailAddress: $charity->getEmailAddress()?->email,
regulatorNumber: $charity->getRegulatorNumber(),
regulatorRegion: $this->getRegionForRegulator($charity->getRegulator()),
logoUri: $charity->getLogoUri()?->__toString(),
stripeAccountId: $charity->getStripeAccountId(),
ryftAccountId: $charity->getRyftAccountId()?->ryftAccountId,
psp: $charity->psp->value,
);
if ($metaCampaign && $metaCampaign->usesSharedFunds()) {
$parentMatchFundsRemaining = $this->cachedMetaCampaignMatchFundsRemaining($metaCampaign)->toMajorUnitFloat();
} else {
$parentMatchFundsRemaining = null;
}
$stats = $campaign->getStatistics();
$bannerUri = $sfCampaignData['bannerUri'] ?? null;
$banner = $sfCampaignData['banner'] ?? null;
if ($banner === null && \is_string($bannerUri)) {
$banner = [
'uri' => $bannerUri, 'alt_text' => null
];
}
/**
* We know that it's sometimes too easy to accidentally duplicate a budget detail line when entering campaign
* details in Salesforce - as each of these duplicates are almost certainly errors so we only output unique
* values. We might consider doing the same for other lists such as aims.
*/
$budgetDetails = \array_values(\array_unique(array: $sfCampaignData['budgetDetails'], flags: \SORT_REGULAR));
$campaignHttpModel = new CampaignHttpModel(
id: $campaign->getSalesforceId(),
amountRaised: $stats->getAmountRaised()->toMajorUnitFloat(),
additionalImageUris: $sfCampaignData['additionalImageUris'], // @todo delete soon
additionalImages: $sfCampaignData['additionalImages'] ?? [],
aims: $sfCampaignData['aims'],
alternativeFundUse: $sfCampaignData['alternativeFundUse'],
banner: $banner,
bannerUri: $bannerUri, // @todo - delete this when FE deploy is done to read 'banner' instead.
beneficiaries: $sfCampaignData['beneficiaries'],
budgetDetails: $budgetDetails,
/* @mat-405-todo - remove this and any other properties that make sense only for meta-campaigns. Will require separating model in FE also */
campaignCount: $sfCampaignData['campaignCount'],
categories: $sfCampaignData['categories'],
championName: $sfCampaignData['championName'],
championOptInStatement: $sfCampaignData['championOptInStatement'],
championRef: $sfCampaignData['championRef'],
charity: $charityHttpModel,
countries: $sfCampaignData['countries'],
currencyCode: $campaign->getCurrencyCode() ?? '',
donationCount: $this->donationRepository->countCompleteDonationsToCampaign($campaign),
endDate: $this->formatDate($campaign->getEndDate()),
hidden: $campaign->isHidden(),
impactReporting: $sfCampaignData['impactReporting'],
impactSummary: $sfCampaignData['impactSummary'],
isMatched: $campaign->isMatched(),
logoUri: $sfCampaignData['logoUri'],
matchFundsRemaining: $stats->getMatchFundsRemaining()->toMajorUnitFloat(),
matchFundsTotal: $stats->getMatchFundsTotal()->toMajorUnitFloat(),
parentMatchFundsRemaining: $parentMatchFundsRemaining,
parentRef: $campaign->getMetaCampaignSlug()?->slug,
parentUsesSharedFunds: $metaCampaign && $metaCampaign->usesSharedFunds(),
problem: $sfCampaignData['problem'],
quotes: $sfCampaignData['quotes'],
ready: $campaign->isReady(),
solution: $sfCampaignData['solution'],
startDate: $this->formatDate($campaign->getStartDate()),
status: $campaignStatus,
isRegularGiving: $campaign->isRegularGiving(),
regularGivingCollectionEnd: $this->formatDate($campaign->getRegularGivingCollectionEnd()),
summary: $sfCampaignData['summary'],
surplusDonationInfo: $sfCampaignData['surplusDonationInfo'],
target: $this->campaignTarget($campaign, $metaCampaign)->toMajorUnitFloat(),
thankYouMessage: $campaign->getThankYouMessage() ?? '',
title: $campaign->getCampaignName(),
updates: $sfCampaignData['updates'],
usesSharedFunds: $sfCampaignData['usesSharedFunds'],
video: $sfCampaignData['video'],
);
/** @var array<string, mixed> $campaignHttpModelArray */
$campaignHttpModelArray = \json_decode(
json: \json_encode($campaignHttpModel, \JSON_THROW_ON_ERROR),
associative: true,
depth: 512,
flags: JSON_THROW_ON_ERROR
);
// In SF a few expired campaigns have null start and end date. Matchbot data model doesn't allow that
// so using 1970 as placeholder for null, and then switching it back to null for display.
// FE will display e.g. "Closed null" but that's existing behaviour that we don't need to fix right now.
if (is_string($campaignHttpModelArray['startDate']) && \str_starts_with($campaignHttpModelArray['startDate'], '1970-01-01')) {
$campaignHttpModelArray['startDate'] = null;
}
if (is_string($campaignHttpModelArray['endDate']) && \str_starts_with($campaignHttpModelArray['endDate'], '1970-01-01')) {
$campaignHttpModelArray['endDate'] = null;
}
// We could just return $sfCampaignData to FE and not need to generate anything else with matchbot
// logic, but that would keep FE indirectly coupled to the SF service. By making sure matchbot is able to
// semi-independently regenerate the same thing we should be able to break the dependency and then later evolve
// the mathbot<->frontend interface without needing to change SF.
try {
CampaignRenderCompatibilityChecker::checkCampaignHttpModelMatchesModelFromSF($campaignHttpModelArray, $sfCampaignData);
} catch (LazyAssertionException $exception) {
$errorMessages = \array_map(
fn(InvalidArgumentException $e) => "{$e->getPropertyPath()}: {$e->getMessage()}",
$exception->getErrorExceptions()
);
\ksort($errorMessages);
$campaignHttpModelArray['errors'] = $errorMessages;
}
return $campaignHttpModelArray;
}
/**
* Formats a date exactly as our SF API would, to allow easy checking for compatibility, returns e.g.
* "2025-08-01T15:33:00.000Z"
*
* @psalm-param null|\DateTimeInterface $dateTime
* @psalm-return ($dateTime is \DateTimeInterface ? string : null|string)
*/
private function formatDate(?\DateTimeInterface $dateTime): ?string
{
if ($dateTime === null) {
return null;
}
/** e.g. 2025-08-01T15:33:00Z */
$formatted = $dateTime->format('Y-m-d\TH:i:sp');
// I'm assuming the milliseconds part of all times served from our SF API is zero, since it seems to be
// in tests and I can't imagine we ever need sub-second precision.
return \str_replace('Z', '.000Z', $formatted);
}
/**
* @psalm-param key-of<CampaignDomainModel::REGULATORS> |null $regulator
* @phpstan-param 'CCEW'|'OSCR'|'CCNI'|null $regulator
*/
private function getRegionForRegulator(?string $regulator): string
{
return match ($regulator) {
'CCEW' => 'England and Wales',
'OSCR' => 'Scotland',
'CCNI' => 'Northern Ireland',
null => 'Exempt', // have to assume the charity is exempt if not using any of the above regulators.
};
}
private function cachedMetaCampaignMatchFundsTotal(MetaCampaign $metaCampaign): Money
{
$id = $metaCampaign->getId();
if ($id === null) {
return Money::zero($metaCampaign->getCurrency());
}
$cachedAmountArray = $this->cache->get(
key: self::METACAMPAIGN_MATCH_FUNDS_TOTAL_PREFIX . (string)$id,
callback: function (ItemInterface $item) use ($metaCampaign): array {
$item->expiresAfter(120); // two minutes
return $this->matchFundsService->getFundsTotalForMetaCampaign($metaCampaign)->jsonSerialize();
}
);
return Money::fromSerialized($cachedAmountArray);
}
private function cachedMetaCampaignMatchFundsRemaining(MetaCampaign $metaCampaign): Money
{
$id = $metaCampaign->getId();
if ($id === null) {
return Money::zero($metaCampaign->getCurrency());
}
$cachedAmountArray = $this->cache->get(
key: self::METACAMPAIGN_MATCH_AMOUNT_REMAINING_PREFIX . (string)$id,
callback: function (ItemInterface $item) use ($metaCampaign): array {
$item->expiresAfter(120); // two minutes
$startTime = $this->clock->now();
$returnValue = $this->matchFundsService->getFundsRemainingForMetaCampaign($metaCampaign)->jsonSerialize();
$endTime = $this->clock->now();
$diffSeconds = $startTime->diff($endTime)->f;
$this->log->info("getFundsRemainingForMetaCampaign {$metaCampaign->getSalesforceId()} took " . (string) $diffSeconds . "s");
return $returnValue;
}
);
return Money::fromSerialized($cachedAmountArray);
}
public function getAmountRaisedForMetaCampaign(MetaCampaign $metaCampaign): Money
{
$id = $metaCampaign->getId();
Assertion::notNull($id);
$cachedAmountArray = $this->cache->get(
key: self::METACAMPAIGN_MATCH_AMOUNT_RAISED_PREFIX . (string)$id,
callback: function (ItemInterface $item) use ($metaCampaign): array {
$item->expiresAfter(120); // two minutes
return $this->metaCampaignRepository->totalAmountRaised($metaCampaign)->jsonSerialize();
}
);
return Money::fromSerialized($cachedAmountArray);
}
}