Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.JdbcType;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.dialect.PostgreSQLJsonPGObjectJsonType;
import org.hibernate.type.SqlTypes;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
Expand Down Expand Up @@ -39,7 +41,8 @@ public class FileUpload {
@Column(name = "skipped_rows") private Integer skippedRows;
@Column(name = "duplicate_rows") private Integer duplicateRows;

@JdbcTypeCode(SqlTypes.JSON)
// Plain json, not jsonb: jsonb reorders keys and the columns must stay in file order (V26)
@JdbcType(PostgreSQLJsonPGObjectJsonType.class)
@Column(name = "column_preview")
private Map<String, Object> columnPreview;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,15 @@
import com.mailengine.mailengine.entity.CampaignRecipientList;
import com.mailengine.mailengine.entity.CampaignRecipientListId;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface CampaignRecipientListRepository extends JpaRepository<CampaignRecipientList, CampaignRecipientListId> {
List<CampaignRecipientList> findByCampaignId(Long campaignId);

/** How many campaigns send to the list (a list in use can't be deleted). */
@Query("select count(c) from CampaignRecipientList c where c.id.recipientListId = :listId")
long countCampaignsUsing(@Param("listId") Long listId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
@Repository
public interface CampaignRepository extends JpaRepository<Campaign, Long> {

/** How many campaigns use the template (a template in use can't be deleted). */
long countByTemplateId(Long templateId);

Page<Campaign> findByStatus(CampaignStatus status, Pageable pageable);

/** Scheduled campaigns whose send time has arrived. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
import com.mailengine.mailengine.dto.response.RecipientListResponse;
import com.mailengine.mailengine.entity.Recipient;
import com.mailengine.mailengine.entity.RecipientList;
import com.mailengine.mailengine.exception.ConflictException;
import com.mailengine.mailengine.exception.ResourceNotFoundException;
import com.mailengine.mailengine.repository.CampaignRecipientListRepository;
import com.mailengine.mailengine.repository.RecipientListRepository;
import com.mailengine.mailengine.repository.RecipientRepository;
import lombok.RequiredArgsConstructor;
Expand All @@ -24,6 +26,7 @@
public class RecipientListService {

private final RecipientListRepository recipientListRepository;
private final CampaignRecipientListRepository campaignRecipientListRepository;
private final RecipientRepository recipientRepository;

@Transactional(readOnly = true)
Expand Down Expand Up @@ -52,7 +55,14 @@ public RecipientListResponse updateList(Long id, CreateRecipientListRequest requ
}

public void deleteList(Long id) {
recipientListRepository.delete(findOrThrow(id));
RecipientList list = findOrThrow(id);
long campaigns = campaignRecipientListRepository.countCampaignsUsing(id);
if (campaigns > 0) {
throw new ConflictException(String.format(
"This list is used by %d campaign%s. Delete those campaigns or remove the list from them first.",
campaigns, campaigns == 1 ? "" : "s"));
}
recipientListRepository.delete(list);
}

@Transactional(readOnly = true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
import com.mailengine.mailengine.entity.Template;
import com.mailengine.mailengine.entity.User;
import com.mailengine.mailengine.exception.BadRequestException;
import com.mailengine.mailengine.exception.ConflictException;
import com.mailengine.mailengine.exception.ResourceNotFoundException;
import com.mailengine.mailengine.repository.CampaignRepository;
import com.mailengine.mailengine.repository.TemplateRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -27,6 +29,7 @@
public class TemplateService {

private final TemplateRepository templateRepository;
private final CampaignRepository campaignRepository;
private final S3Service s3Service;

public String uploadImage(MultipartFile file) {
Expand Down Expand Up @@ -94,7 +97,14 @@ public String parseUploadedHtml(MultipartFile file) {
}

public void deleteTemplate(Long id) {
templateRepository.delete(findOrThrow(id));
Template template = findOrThrow(id);
long campaigns = campaignRepository.countByTemplateId(id);
if (campaigns > 0) {
throw new ConflictException(String.format(
"This template is used by %d campaign%s. Delete those campaigns or give them another template first.",
campaigns, campaigns == 1 ? "" : "s"));
}
templateRepository.delete(template);
}

private Template findOrThrow(Long id) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
-- JSONB reorders object keys, so an upload's columns came back out of file order (the mapping screen showed
-- them shuffled). JSON keeps the text as written, so the order is kept.
ALTER TABLE file_uploads
ALTER COLUMN column_preview TYPE JSON USING column_preview::json;

-- Deleting a recipient list failed (409) once anything had been uploaded to it: its upload history now goes
-- with it (and any file still waiting for a column mapping, through pending_upload_files' own cascade).
ALTER TABLE file_uploads
DROP CONSTRAINT file_uploads_recipient_list_id_fkey,
ADD CONSTRAINT file_uploads_recipient_list_id_fkey
FOREIGN KEY (recipient_list_id) REFERENCES recipient_lists (id) ON DELETE CASCADE;
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ void oddHeadersWaitForAMappingThenImport() throws Exception {
assertThat(status.get("status").asText()).isEqualTo("failed");
assertThat(status.get("needsMapping").asBoolean()).isTrue();
assertThat(status.get("columns")).extracting(JsonNode::asText)
.containsExactlyInAnyOrder("e-mail", "given name", "surname", "notes");
.as("in file order").containsExactly("e-mail", "given name", "surname", "notes");
assertThat(status.get("preview").get(0).get("e-mail").asText())
.as("the mapping screen shows a sample value per column").isEqualTo("map1@example.test");
assertThat(members()).isZero();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,37 @@ void onlyHtmlFilesAreAcceptedAsTemplates() throws Exception {
.andExpect(status().isBadRequest());
}

@Test
void templatesAndListsInUseAreRefusedWithAClearReason() throws Exception {
long template = jdbc.queryForObject("insert into templates (name, html_content) values ('Used', '<p/>') returning id", Long.class);
long list = jdbc.queryForObject("insert into recipient_lists (name) values ('Used') returning id", Long.class);
long campaign = jdbc.queryForObject("insert into campaigns (name, subject_line, from_name, from_email, template_id) "
+ "values ('User', 'S', 'F', 'f@example.test', ?) returning id", Long.class, template);
jdbc.update("insert into campaign_recipient_lists (campaign_id, recipient_list_id) values (?, ?)", campaign, list);

mvc.perform(delete("/api/templates/{id}", template).with(authentication(ADMIN)))
.andExpect(status().isConflict())
.andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("used by 1 campaign")));
mvc.perform(delete("/api/recipient-lists/{id}", list).with(authentication(ADMIN)))
.andExpect(status().isConflict())
.andExpect(jsonPath("$.message").value(org.hamcrest.Matchers.containsString("used by 1 campaign")));
assertThat(jdbc.queryForObject("select count(*) from templates where id = ?", Integer.class, template)).isOne();
assertThat(jdbc.queryForObject("select count(*) from recipient_lists where id = ?", Integer.class, list)).isOne();
}

@Test
void aListWithUploadsCanBeDeleted() throws Exception {
long list = jdbc.queryForObject("insert into recipient_lists (name) values ('Uploaded to') returning id", Long.class);
long upload = jdbc.queryForObject("insert into file_uploads (recipient_list_id, file_name, status) "
+ "values (?, 'odd.csv', 'failed') returning id", Long.class, list);
jdbc.update("insert into pending_upload_files (upload_id, file_name, content) values (?, 'odd.csv', '\\x00')", upload);

mvc.perform(delete("/api/recipient-lists/{id}", list).with(authentication(ADMIN))).andExpect(status().isNoContent());

assertThat(jdbc.queryForObject("select count(*) from file_uploads where id = ?", Integer.class, upload)).isZero();
assertThat(jdbc.queryForObject("select count(*) from pending_upload_files where upload_id = ?", Integer.class, upload)).isZero();
}

@Test
void testSendNeedsValidAddresses() throws Exception {
for (String body : new String[]{"{}", "{\"testEmails\": []}", "{\"testEmails\": [\"not-an-email\"]}",
Expand Down
Loading