Initial commit

This commit is contained in:
root
2026-01-19 17:44:46 +01:00
commit 823af8b11d
8721 changed files with 1130846 additions and 0 deletions

View File

@@ -0,0 +1,74 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Modules\Crm\Tools\Campaign\Api;
use Espo\Core\Acl;
use Espo\Core\Acl\Table;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Forbidden;
use Espo\Modules\Crm\Entities\Campaign;
use Espo\Modules\Crm\Tools\Campaign\MailMergeService;
/**
* Generates mail merge PDFs.
*/
class PostGenerateMailMerge implements Action
{
public function __construct(
private MailMergeService $service,
private Acl $acl
) {}
public function process(Request $request): Response
{
$id = $request->getRouteParam('id');
$link = $request->getParsedBody()->link ?? null;
if (!$id) {
throw new BadRequest();
}
if (!$link) {
throw new BadRequest("No `link`.");
}
if (!$this->acl->checkScope(Campaign::ENTITY_TYPE, Table::ACTION_READ)) {
throw new Forbidden();
}
$attachmentId = $this->service->generate($id, $link);
return ResponseComposer::json(['id' => $attachmentId]);
}
}

View File

@@ -0,0 +1,333 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Modules\Crm\Tools\Campaign;
use Espo\Core\Field\DateTime;
use Espo\Core\Utils\Config;
use Espo\Entities\EmailTemplate;
use Espo\Modules\Crm\Entities\CampaignLogRecord;
use Espo\Modules\Crm\Entities\CampaignTrackingUrl;
use Espo\Modules\Crm\Entities\EmailQueueItem as QueueItem;
use Espo\Modules\Crm\Entities\Lead;
use Espo\Modules\Crm\Entities\MassEmail;
use Espo\ORM\Entity;
use Espo\ORM\EntityManager;
class LogService
{
private EntityManager $entityManager;
private Config $config;
public function __construct(
EntityManager $entityManager,
Config $config
) {
$this->entityManager = $entityManager;
$this->config = $config;
}
public function logLeadCreated(string $campaignId, Lead $target): void
{
$actionDate = DateTime::createNow();
$logRecord = $this->entityManager->getNewEntity(CampaignLogRecord::ENTITY_TYPE);
$logRecord->set([
'campaignId' => $campaignId,
'actionDate' => $actionDate->toString(),
'parentId' => $target->getId(),
'parentType' => $target->getEntityType(),
'action' => CampaignLogRecord::ACTION_LEAD_CREATED,
]);
$this->entityManager->saveEntity($logRecord);
}
public function logSent(string $campaignId, QueueItem $queueItem, ?Entity $emailOrEmailTemplate = null): void
{
$queueItemId = $queueItem->getId();
$isTest = $queueItem->isTest();
$actionDate = DateTime::createNow();
$logRecord = $this->entityManager->getNewEntity(CampaignLogRecord::ENTITY_TYPE);
$logRecord->set([
'campaignId' => $campaignId,
'actionDate' => $actionDate->toString(),
'parentId' => $queueItem->getTargetId(),
'parentType' => $queueItem->getTargetType(),
'action' => CampaignLogRecord::ACTION_SENT,
'stringData' => $queueItem->getEmailAddress(),
'queueItemId' => $queueItemId,
'isTest' => $isTest,
]);
if ($emailOrEmailTemplate) {
$logRecord->set([
'objectId' => $emailOrEmailTemplate->getId(),
'objectType' => $emailOrEmailTemplate->getEntityType()
]);
}
$this->entityManager->saveEntity($logRecord);
}
public function logBounced(string $campaignId, QueueItem $queueItem, bool $isHard = false): void
{
$queueItemId = $queueItem->getId();
$isTest = $queueItem->isTest();
$emailAddress = $queueItem->getEmailAddress();
if (
$this->entityManager
->getRDBRepository(CampaignLogRecord::ENTITY_TYPE)
->where([
'queueItemId' => $queueItemId,
'action' => CampaignLogRecord::ACTION_BOUNCED,
'isTest' => $isTest,
])
->findOne()
) {
return;
}
$actionDate = DateTime::createNow();
$logRecord = $this->entityManager->getNewEntity(CampaignLogRecord::ENTITY_TYPE);
$logRecord->set([
'campaignId' => $campaignId,
'actionDate' => $actionDate->toString(),
'parentId' => $queueItem->getTargetId(),
'parentType' => $queueItem->getTargetType(),
'action' => CampaignLogRecord::ACTION_BOUNCED,
'stringData' => $emailAddress,
'queueItemId' => $queueItemId,
'isTest' => $isTest,
]);
$logRecord->set(
'stringAdditionalData',
$isHard ?
CampaignLogRecord::BOUNCED_TYPE_HARD :
CampaignLogRecord::BOUNCED_TYPE_SOFT
);
$this->entityManager->saveEntity($logRecord);
}
public function logOptedIn(
string $campaignId,
?QueueItem $queueItem,
Entity $target,
?string $emailAddress = null
): void {
if (
$queueItem &&
$this->entityManager
->getRDBRepository(CampaignLogRecord::ENTITY_TYPE)
->where([
'queueItemId' => $queueItem->getId(),
'action' => CampaignLogRecord::ACTION_OPTED_IN,
'isTest' => $queueItem->isTest(),
])
->findOne()
) {
return;
}
$actionDate = DateTime::createNow();
$emailAddress = $emailAddress ?? $target->get('emailAddress');
if (!$emailAddress && $queueItem) {
$emailAddress = $queueItem->getEmailAddress();
}
$queueItemId = null;
$isTest = false;
if ($queueItem) {
$queueItemId = $queueItem->getId();
$isTest = $queueItem->isTest();
}
$logRecord = $this->entityManager->getNewEntity(CampaignLogRecord::ENTITY_TYPE);
$logRecord->set([
'campaignId' => $campaignId,
'actionDate' => $actionDate->toString(),
'parentId' => $target->getId(),
'parentType' => $target->getEntityType(),
'action' => CampaignLogRecord::ACTION_OPTED_IN,
'stringData' => $emailAddress,
'queueItemId' => $queueItemId,
'isTest' => $isTest,
]);
$this->entityManager->saveEntity($logRecord);
}
public function logOptedOut(
string $campaignId,
?QueueItem $queueItem,
Entity $target,
?string $emailAddress = null
): void {
if (
$queueItem &&
$this->entityManager
->getRDBRepository(CampaignLogRecord::ENTITY_TYPE)
->where([
'queueItemId' => $queueItem->getId(),
'action' => CampaignLogRecord::ACTION_OPTED_OUT,
'isTest' => $queueItem->isTest(),
])
->findOne()
) {
return;
}
$actionDate = DateTime::createNow();
$queueItemId = null;
$isTest = false;
if ($queueItem) {
$queueItemId = $queueItem->getId();
$isTest = $queueItem->isTest();
}
if (!$emailAddress && $queueItem) {
$emailAddress = $queueItem->getEmailAddress();
}
$logRecord = $this->entityManager->getNewEntity(CampaignLogRecord::ENTITY_TYPE);
$logRecord->set([
'campaignId' => $campaignId,
'actionDate' => $actionDate->toString(),
'parentId' => $target->getId(),
'parentType' => $target->getEntityType(),
'action' => CampaignLogRecord::ACTION_OPTED_OUT,
'stringData' => $emailAddress,
'queueItemId' => $queueItemId,
'isTest' => $isTest
]);
$this->entityManager->saveEntity($logRecord);
}
public function logOpened(string $campaignId, QueueItem $queueItem): void
{
$actionDate = DateTime::createNow();
if (
$this->entityManager
->getRDBRepository(CampaignLogRecord::ENTITY_TYPE)
->where([
'queueItemId' => $queueItem->getId(),
'action' => CampaignLogRecord::ACTION_OPENED,
'isTest' => $queueItem->isTest(),
])
->findOne()
) {
return;
}
$massEmail = $queueItem->getMassEmail();
if (!$massEmail) {
return;
}
$logRecord = $this->entityManager->getNewEntity(CampaignLogRecord::ENTITY_TYPE);
$logRecord->set([
'campaignId' => $campaignId,
'actionDate' => $actionDate->toString(),
'parentId' => $queueItem->getTargetId(),
'parentType' => $queueItem->getTargetType(),
'action' => CampaignLogRecord::ACTION_OPENED,
'objectId' => $massEmail->getEmailTemplateId(),
'objectType' => EmailTemplate::ENTITY_TYPE,
'queueItemId' => $queueItem->getId(),
'isTest' => $queueItem->isTest(),
]);
$this->entityManager->saveEntity($logRecord);
}
public function logClicked(
string $campaignId,
QueueItem $queueItem,
CampaignTrackingUrl $trackingUrl
): void {
$actionDate = DateTime::createNow();
if ($this->config->get('massEmailOpenTracking')) {
$this->logOpened($campaignId, $queueItem);
}
if (
$this->entityManager
->getRDBRepository(CampaignLogRecord::ENTITY_TYPE)
->where([
'queueItemId' => $queueItem->getId(),
'action' => CampaignLogRecord::ACTION_CLICKED,
'objectId' => $trackingUrl->getId(),
'objectType' => $trackingUrl->getEntityType(),
'isTest' => $queueItem->isTest(),
])
->findOne()
) {
return;
}
$logRecord = $this->entityManager->getNewEntity(CampaignLogRecord::ENTITY_TYPE);
$logRecord->set([
'campaignId' => $campaignId,
'actionDate' => $actionDate->toString(),
'parentId' => $queueItem->getTargetId(),
'parentType' => $queueItem->getTargetType(),
'action' => CampaignLogRecord::ACTION_CLICKED,
'objectId' => $trackingUrl->getId(),
'objectType' => $trackingUrl->getEntityType(),
'queueItemId' => $queueItem->getId(),
'isTest' => $queueItem->isTest(),
]);
$this->entityManager->saveEntity($logRecord);
}
}

View File

@@ -0,0 +1,159 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Modules\Crm\Tools\Campaign;
use Espo\Core\Exceptions\Error;
use Espo\Core\Field\LinkParent;
use Espo\Core\FileStorage\Manager as FileStorageManager;
use Espo\Core\Record\ServiceContainer;
use Espo\Core\Utils\Config;
use Espo\Core\Utils\Util;
use Espo\Entities\Attachment;
use Espo\Entities\Template;
use Espo\Modules\Crm\Entities\Campaign;
use Espo\ORM\Entity;
use Espo\ORM\EntityCollection;
use Espo\ORM\EntityManager;
use Espo\Tools\Pdf\Builder;
use Espo\Tools\Pdf\Data\DataLoaderManager;
use Espo\Tools\Pdf\IdDataMap;
use Espo\Tools\Pdf\Params;
use Espo\Tools\Pdf\TemplateWrapper;
use Espo\Tools\Pdf\ZipContents;
class MailMergeGenerator
{
private const DEFAULT_ENGINE = 'Dompdf';
private const ATTACHMENT_MAIL_MERGE_ROLE = 'Mail Merge';
private EntityManager $entityManager;
private DataLoaderManager $dataLoaderManager;
private ServiceContainer $serviceContainer;
private Builder $builder;
private Config $config;
private FileStorageManager $fileStorageManager;
public function __construct(
EntityManager $entityManager,
DataLoaderManager $dataLoaderManager,
ServiceContainer $serviceContainer,
Builder $builder,
Config $config,
FileStorageManager $fileStorageManager
) {
$this->entityManager = $entityManager;
$this->dataLoaderManager = $dataLoaderManager;
$this->serviceContainer = $serviceContainer;
$this->builder = $builder;
$this->config = $config;
$this->fileStorageManager = $fileStorageManager;
}
/**
* Generate a mail-merge PDF.
*
* @return string An attachment ID.
* @param EntityCollection<Entity> $collection
* @throws Error
*/
public function generate(
EntityCollection $collection,
Template $template,
?string $campaignId = null,
?string $name = null
): string {
$entityType = $collection->getEntityType();
if (!$entityType) {
throw new Error("No entity type.");
}
$name = $name ?? $campaignId ?? $entityType;
$params = Params::create()->withAcl();
$idDataMap = IdDataMap::create();
$service = $this->serviceContainer->get($entityType);
foreach ($collection as $entity) {
$service->loadAdditionalFields($entity);
$idDataMap->set(
$entity->getId(),
$this->dataLoaderManager->load($entity, $params)
);
// For bc.
if (method_exists($service, 'loadAdditionalFieldsForPdf')) {
$service->loadAdditionalFieldsForPdf($entity);
}
}
$engine = $this->config->get('pdfEngine') ?? self::DEFAULT_ENGINE;
$templateWrapper = new TemplateWrapper($template);
$printer = $this->builder
->setTemplate($templateWrapper)
->setEngine($engine)
->build();
$contents = $printer->printCollection($collection, $params, $idDataMap);
$type = $contents instanceof ZipContents ?
'application/zip' :
'application/pdf';
$filename = $contents instanceof ZipContents ?
Util::sanitizeFileName($name) . '.zip' :
Util::sanitizeFileName($name) . '.pdf';
/** @var Attachment $attachment */
$attachment = $this->entityManager->getNewEntity(Attachment::ENTITY_TYPE);
$relatedLink = $campaignId ?
LinkParent::create(Campaign::ENTITY_TYPE, $campaignId) : null;
$attachment
->setRelated($relatedLink)
->setSize($contents->getStream()->getSize())
->setRole(self::ATTACHMENT_MAIL_MERGE_ROLE)
->setName($filename)
->setType($type);
$this->entityManager->saveEntity($attachment);
$this->fileStorageManager->putStream($attachment, $contents->getStream());
return $attachment->getId();
}
}

View File

@@ -0,0 +1,231 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2025 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Modules\Crm\Tools\Campaign;
use Espo\Core\Acl;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Error;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Utils\Language;
use Espo\Entities\Template;
use Espo\Modules\Crm\Entities\Campaign as CampaignEntity;
use Espo\Modules\Crm\Entities\TargetList;
use Espo\ORM\Collection;
use Espo\ORM\Defs\Params\RelationParam;
use Espo\ORM\Entity;
use Espo\ORM\EntityCollection;
use Espo\ORM\EntityManager;
class MailMergeService
{
/** @var array<string, string[]> */
protected $entityTypeAddressFieldListMap = [
'Account' => ['billingAddress', 'shippingAddress'],
'Contact' => ['address'],
'Lead' => ['address'],
'User' => [],
];
/** @var string[] */
protected $targetLinkList = [
'accounts',
'contacts',
'leads',
'users',
];
private EntityManager $entityManager;
private Acl $acl;
private Language $defaultLanguage;
private MailMergeGenerator $generator;
public function __construct(
EntityManager $entityManager,
Acl $acl,
Language $defaultLanguage,
MailMergeGenerator $generator
) {
$this->entityManager = $entityManager;
$this->acl = $acl;
$this->defaultLanguage = $defaultLanguage;
$this->generator = $generator;
}
/**
* @return string An attachment ID.
* @throws BadRequest
* @throws Error
* @throws Forbidden
*/
public function generate(string $campaignId, string $link, bool $checkAcl = true): string
{
/** @var CampaignEntity $campaign */
$campaign = $this->entityManager->getEntityById(CampaignEntity::ENTITY_TYPE, $campaignId);
if ($checkAcl && !$this->acl->checkEntityRead($campaign)) {
throw new Forbidden();
}
/** @var string $targetEntityType */
$targetEntityType = $campaign->getRelationParam($link, RelationParam::ENTITY);
if ($checkAcl && !$this->acl->check($targetEntityType, Acl\Table::ACTION_READ)) {
throw new Forbidden("Could not mail merge campaign because access to target entity type is forbidden.");
}
if (!in_array($link, $this->targetLinkList)) {
throw new BadRequest();
}
if ($campaign->getType() !== CampaignEntity::TYPE_MAIL) {
throw new Error("Could not mail merge campaign not of Mail type.");
}
$templateId = $campaign->get($link . 'TemplateId');
if (!$templateId) {
throw new Error("Could not mail merge campaign w/o specified template.");
}
/** @var ?Template $template */
$template = $this->entityManager->getEntityById(Template::ENTITY_TYPE, $templateId);
if (!$template) {
throw new Error("Template not found.");
}
if ($template->getTargetEntityType() !== $targetEntityType) {
throw new Error("Template is not of proper entity type.");
}
$campaign->loadLinkMultipleField('targetLists');
$campaign->loadLinkMultipleField('excludingTargetLists');
if (count($campaign->getLinkMultipleIdList('targetLists')) === 0) {
throw new Error("Could not mail merge campaign w/o any specified target list.");
}
$metTargetHash = [];
$targetEntityList = [];
/** @var Collection<TargetList> $excludingTargetListList */
$excludingTargetListList = $this->entityManager
->getRDBRepository(CampaignEntity::ENTITY_TYPE)
->getRelation($campaign, 'excludingTargetLists')
->find();
foreach ($excludingTargetListList as $excludingTargetList) {
$recordList = $this->entityManager
->getRDBRepository(TargetList::ENTITY_TYPE)
->getRelation($excludingTargetList, $link)
->find();
foreach ($recordList as $excludingTarget) {
$hashId = $excludingTarget->getEntityType() . '-' . $excludingTarget->getId();
$metTargetHash[$hashId] = true;
}
}
$addressFieldList = $this->entityTypeAddressFieldListMap[$targetEntityType];
/** @var Collection<TargetList> $targetListCollection */
$targetListCollection = $this->entityManager
->getRDBRepository(CampaignEntity::ENTITY_TYPE)
->getRelation($campaign, 'targetLists')
->find();
foreach ($targetListCollection as $targetList) {
if (!$campaign->get($link . 'TemplateId')) {
continue;
}
$entityList = $this->entityManager
->getRDBRepository(TargetList::ENTITY_TYPE)
->getRelation($targetList, $link)
->where([
'@relation.optedOut' => false,
])
->find();
foreach ($entityList as $e) {
$hashId = $e->getEntityType() . '-'. $e->getId();
if (!empty($metTargetHash[$hashId])) {
continue;
}
$metTargetHash[$hashId] = true;
if ($campaign->get('mailMergeOnlyWithAddress')) {
if (empty($addressFieldList)) {
continue;
}
$hasAddress = false;
foreach ($addressFieldList as $addressField) {
if (
$e->get($addressField . 'Street') ||
$e->get($addressField . 'PostalCode')
) {
$hasAddress = true;
break;
}
}
if (!$hasAddress) {
continue;
}
}
$targetEntityList[] = $e;
}
}
if (empty($targetEntityList)) {
throw new Error("No targets available for mail merge.");
}
$filename = $campaign->getName() . ' - ' .
$this->defaultLanguage->translateLabel($targetEntityType, 'scopeNamesPlural');
/** @var EntityCollection<Entity> $collection */
$collection = $this->entityManager
->getCollectionFactory()
->create($targetEntityType, $targetEntityList);
return $this->generator->generate(
$collection,
$template,
$campaign->getId(),
$filename
);
}
}