CustomerService.java

1
package com.rbctcsworld.ecommerce.customer;
2
3
import com.rbctcsworld.ecommerce.audit.AuditChange;
4
import com.rbctcsworld.ecommerce.audit.AuditEvent;
5
import com.rbctcsworld.ecommerce.auth.AppUser;
6
import com.rbctcsworld.ecommerce.auth.RefreshTokenRepository;
7
import com.rbctcsworld.ecommerce.auth.Role;
8
import com.rbctcsworld.ecommerce.auth.UserRepository;
9
import com.rbctcsworld.ecommerce.common.exception.BusinessRuleException;
10
import com.rbctcsworld.ecommerce.common.exception.NotFoundException;
11
import com.rbctcsworld.ecommerce.customer.CustomerDtos.CustomerDetail;
12
import com.rbctcsworld.ecommerce.customer.CustomerDtos.CustomerOrder;
13
import com.rbctcsworld.ecommerce.customer.CustomerDtos.CustomerPage;
14
import com.rbctcsworld.ecommerce.customer.CustomerDtos.CustomerSummary;
15
import com.rbctcsworld.ecommerce.customer.CustomerDtos.LastAddress;
16
import org.springframework.context.ApplicationEventPublisher;
17
import org.springframework.jdbc.core.JdbcTemplate;
18
import org.springframework.jdbc.core.RowMapper;
19
import org.springframework.stereotype.Service;
20
import org.springframework.transaction.annotation.Transactional;
21
22
import java.sql.Timestamp;
23
import java.time.Clock;
24
import java.time.LocalDateTime;
25
import java.util.ArrayList;
26
import java.util.List;
27
import java.util.Locale;
28
import java.util.Map;
29
30
/**
31
 * Customer accounts for the store admin: browse, search, look at one customer, disable / enable.
32
 * Store admins are not listed and cannot be disabled here. Passwords are never read or shown.
33
 */
34
@Service
35
@Transactional
36
public class CustomerService {
37
38
    public static final int MAX_SIZE = 100;
39
    /** Sort keys the list accepts (anything else: 400). Every order ends with the id, so pages are stable. */
40
    public static final Map<String, String> SORTS = Map.of(
41
            "newest", "u.created_at desc, u.id desc",
42
            "email", "u.email asc, u.id asc",
43
            "orders", "order_count desc, u.id asc",
44
            "spent", "spent desc, u.id asc",
45
            "lastOrder", "last_order_at desc nulls last, u.id asc");
46
    /** Statuses that count as money received (CANCELLED and RETURNED were refunded). */
47
    static final String PAID_STATUSES = "'PAID', 'SHIPPED', 'DELIVERED', 'RETURN_REQUESTED'";
48
49
    private static final String SELECT = """
50
            select u.id, u.email, u.active, u.created_at,
51
                   count(o.id) as order_count,
52
                   coalesce(sum(case when o.status in (%s) then o.total else 0 end), 0) as spent,
53
                   max(o.created_at) as last_order_at
54
            from users u left join orders o on o.user_id = u.id
55
            """.formatted(PAID_STATUSES);
56
    private static final String GROUP = " group by u.id, u.email, u.active, u.created_at";
57
58
    private static final RowMapper<CustomerSummary> SUMMARY = (rs, i) -> new CustomerSummary(rs.getLong("id"),
59
            rs.getString("email"), rs.getBoolean("active"), time(rs.getTimestamp("created_at")), rs.getLong("order_count"),
60
            rs.getBigDecimal("spent").setScale(2), time(rs.getTimestamp("last_order_at")));
61
62
    private final JdbcTemplate jdbc;
63
    private final UserRepository users;
64
    private final RefreshTokenRepository refreshTokens;
65
    private final ApplicationEventPublisher events;
66
    private final Clock clock;
67
68
    public CustomerService(JdbcTemplate jdbc, UserRepository users, RefreshTokenRepository refreshTokens,
69
                           ApplicationEventPublisher events, Clock clock) {
70
        this.jdbc = jdbc;
71
        this.users = users;
72
        this.refreshTokens = refreshTokens;
73
        this.events = events;
74
        this.clock = clock;
75
    }
76
77
    /**
78
     * q: part of the e-mail (case-insensitive); status: ACTIVE | DISABLED | null (all);
79
     * sort: newest (default) | email | orders | spent | lastOrder; page from 0; size 1..100 (default 20).
80
     */
81
    @Transactional(readOnly = true)
82
    public CustomerPage search(String q, String status, String sort, Integer page, Integer size) {
83 1 1. search : removed conditional - replaced equality check with false → KILLED
        int p = page == null ? 0 : page;
84 1 1. search : removed conditional - replaced equality check with false → KILLED
        int n = size == null ? 20 : size;
85 2 1. search : removed conditional - replaced comparison check with false → KILLED
2. search : changed conditional boundary → KILLED
        if (p < 0) throw new BusinessRuleException("page must be 0 or more");
86 4 1. search : changed conditional boundary → KILLED
2. search : removed conditional - replaced comparison check with false → KILLED
3. search : removed conditional - replaced comparison check with false → KILLED
4. search : changed conditional boundary → KILLED
        if (n < 1 || n > MAX_SIZE) throw new BusinessRuleException("size must be between 1 and " + MAX_SIZE);
87 2 1. search : removed conditional - replaced equality check with false → KILLED
2. search : removed conditional - replaced equality check with false → KILLED
        String order = SORTS.get(sort == null || sort.isBlank() ? "newest" : sort.trim());
88 1 1. search : removed conditional - replaced equality check with false → KILLED
        if (order == null) throw new BusinessRuleException("sort must be one of " + new java.util.TreeSet<>(SORTS.keySet()));
89
90
        StringBuilder where = new StringBuilder(" where u.role = '" + Role.CUSTOMER + "'");
91
        List<Object> args = new ArrayList<>();
92 2 1. search : removed conditional - replaced equality check with false → KILLED
2. search : removed conditional - replaced equality check with false → KILLED
        if (q != null && !q.isBlank()) {
93
            where.append(" and lower(u.email) like ? escape '\\'");
94
            args.add("%" + likeEscape(q.trim().toLowerCase(Locale.ROOT)) + "%");
95
        }
96 2 1. search : removed conditional - replaced equality check with false → KILLED
2. search : removed conditional - replaced equality check with false → KILLED
        if (status != null && !status.isBlank()) {
97
            switch (status.trim().toUpperCase(Locale.ROOT)) {
98
                case "ACTIVE" -> where.append(" and u.active = true");
99
                case "DISABLED" -> where.append(" and u.active = false");
100
                default -> throw new BusinessRuleException("status must be ACTIVE or DISABLED");
101
            }
102
        }
103
        Long total = jdbc.queryForObject("select count(*) from users u" + where, Long.class, args.toArray());
104 1 1. search : Replaced long multiplication with division → KILLED
        List<CustomerSummary> items = jdbc.query(SELECT + where + GROUP + " order by " + order
105
                + " limit " + n + " offset " + ((long) p * n), SUMMARY, args.toArray());
106 2 1. search : removed conditional - replaced equality check with false → SURVIVED
2. search : replaced return value with null for com/rbctcsworld/ecommerce/customer/CustomerService::search → KILLED
        return new CustomerPage(items, total == null ? 0 : total, p, n);
107
    }
108
109
    /** The customer with their latest 50 orders and the last delivery address they used. 404 for admins too. */
110
    @Transactional(readOnly = true)
111
    public CustomerDetail detail(long id) {
112
        CustomerSummary summary = summary(id);
113
        List<CustomerOrder> orders = jdbc.query("""
114
                select id, order_number, status, total, created_at from orders
115
                where user_id = ? order by id desc limit 50""",
116 1 1. lambda$detail$1 : replaced return value with null for com/rbctcsworld/ecommerce/customer/CustomerService::lambda$detail$1 → KILLED
                (rs, i) -> new CustomerOrder(rs.getLong("id"), rs.getString("order_number"), rs.getString("status"),
117
                        rs.getBigDecimal("total"), time(rs.getTimestamp("created_at"))), id);
118
        List<LastAddress> address = jdbc.query("""
119
                select ship_name, ship_line1, ship_line2, ship_city, ship_state, ship_zip, ship_phone from orders
120
                where user_id = ? and ship_line1 is not null order by id desc limit 1""",
121 1 1. lambda$detail$2 : replaced return value with null for com/rbctcsworld/ecommerce/customer/CustomerService::lambda$detail$2 → KILLED
                (rs, i) -> new LastAddress(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4),
122
                        rs.getString(5), rs.getString(6), rs.getString(7)), id);
123 2 1. detail : removed conditional - replaced equality check with false → KILLED
2. detail : replaced return value with null for com/rbctcsworld/ecommerce/customer/CustomerService::detail → KILLED
        return new CustomerDetail(summary, orders, address.isEmpty() ? null : address.get(0));
124
    }
125
126
    /**
127
     * Disables (active=false) or enables the account. Disabling also ends every session at once (refresh
128
     * tokens revoked; the access token is refused by JwtFilter on the next request). Setting the state it
129
     * already has changes nothing and records nothing.
130
     */
131
    public CustomerSummary setActive(long id, boolean active) {
132 2 1. lambda$setActive$3 : replaced boolean return with false for com/rbctcsworld/ecommerce/customer/CustomerService::lambda$setActive$3 → KILLED
2. lambda$setActive$3 : replaced boolean return with true for com/rbctcsworld/ecommerce/customer/CustomerService::lambda$setActive$3 → KILLED
        AppUser user = users.findById(id).filter(u -> Role.CUSTOMER.equals(u.getRole()))
133 1 1. lambda$setActive$4 : replaced return value with null for com/rbctcsworld/ecommerce/customer/CustomerService::lambda$setActive$4 → KILLED
                .orElseThrow(() -> new NotFoundException("Customer not found: " + id));
134 1 1. setActive : removed conditional - replaced equality check with false → KILLED
        if (user.isActive() != active) {
135 1 1. setActive : removed call to com/rbctcsworld/ecommerce/auth/AppUser::setActive → KILLED
            user.setActive(active);
136 1 1. setActive : removed conditional - replaced equality check with false → KILLED
            if (!active) refreshTokens.revokeAllOf(id, LocalDateTime.now(clock));
137 1 1. setActive : removed call to org/springframework/context/ApplicationEventPublisher::publishEvent → KILLED
            events.publishEvent(AuditEvent.of(List.of(new AuditChange(AuditChange.CUSTOMER, id,
138 2 1. setActive : removed conditional - replaced equality check with false → KILLED
2. setActive : removed conditional - replaced equality check with false → KILLED
                    active ? "CUSTOMER_ENABLED" : "CUSTOMER_DISABLED", "active",
139
                    Boolean.toString(!active), Boolean.toString(active)))));
140
        }
141 1 1. setActive : removed call to com/rbctcsworld/ecommerce/auth/UserRepository::flush → KILLED
        users.flush();
142 1 1. setActive : replaced return value with null for com/rbctcsworld/ecommerce/customer/CustomerService::setActive → KILLED
        return summary(id);
143
    }
144
145
    private CustomerSummary summary(long id) {
146
        List<CustomerSummary> rows = jdbc.query(SELECT + " where u.id = ? and u.role = '" + Role.CUSTOMER + "'"
147
                + GROUP, SUMMARY, id);
148 1 1. summary : removed conditional - replaced equality check with false → KILLED
        if (rows.isEmpty()) throw new NotFoundException("Customer not found: " + id);
149 1 1. summary : replaced return value with null for com/rbctcsworld/ecommerce/customer/CustomerService::summary → KILLED
        return rows.get(0);
150
    }
151
152
    /** % and _ are wildcards in LIKE: a search for "a_b" must find exactly "a_b". */
153
    static String likeEscape(String s) {
154 1 1. likeEscape : replaced return value with "" for com/rbctcsworld/ecommerce/customer/CustomerService::likeEscape → KILLED
        return s.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_");
155
    }
156
157
    private static LocalDateTime time(Timestamp t) {
158
        return t == null ? null : t.toLocalDateTime();
159
    }
160
}

Mutations

83

1.1
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:everySortOrderAndStablePages()]
removed conditional - replaced equality check with false → KILLED

84

1.1
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:pageAndSizeAreChecked()]
removed conditional - replaced equality check with false → KILLED

85

1.1
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:pageAndSizeAreChecked()]
removed conditional - replaced comparison check with false → KILLED

2.2
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:pageAndSizeAreChecked()]
changed conditional boundary → KILLED

86

1.1
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:pageAndSizeAreChecked()]
changed conditional boundary → KILLED

2.2
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:pageAndSizeAreChecked()]
removed conditional - replaced comparison check with false → KILLED

3.3
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:pageAndSizeAreChecked()]
removed conditional - replaced comparison check with false → KILLED

4.4
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:pageAndSizeAreChecked()]
changed conditional boundary → KILLED

87

1.1
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:searchMatchesPartOfTheEmailLiterallyAndFiltersByStatus()]
removed conditional - replaced equality check with false → KILLED

2.2
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:everySortOrderAndStablePages()]
removed conditional - replaced equality check with false → KILLED

88

1.1
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:everySortOrderAndStablePages()]
removed conditional - replaced equality check with false → KILLED

92

1.1
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:searchMatchesPartOfTheEmailLiterallyAndFiltersByStatus()]
removed conditional - replaced equality check with false → KILLED

2.2
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:searchMatchesPartOfTheEmailLiterallyAndFiltersByStatus()]
removed conditional - replaced equality check with false → KILLED

96

1.1
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:searchMatchesPartOfTheEmailLiterallyAndFiltersByStatus()]
removed conditional - replaced equality check with false → KILLED

2.2
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:searchMatchesPartOfTheEmailLiterallyAndFiltersByStatus()]
removed conditional - replaced equality check with false → KILLED

104

1.1
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:everySortOrderAndStablePages()]
Replaced long multiplication with division → KILLED

106

1.1
Location : search
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:pageAndSizeAreChecked()]
replaced return value with null for com/rbctcsworld/ecommerce/customer/CustomerService::search → KILLED

2.2
Location : search
Killed by : none
removed conditional - replaced equality check with false → SURVIVED
Covering tests

116

1.1
Location : lambda$detail$1
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:theDetailHasTheOrdersNewestFirstAndTheLastAddress()]
replaced return value with null for com/rbctcsworld/ecommerce/customer/CustomerService::lambda$detail$1 → KILLED

121

1.1
Location : lambda$detail$2
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:theDetailHasTheOrdersNewestFirstAndTheLastAddress()]
replaced return value with null for com/rbctcsworld/ecommerce/customer/CustomerService::lambda$detail$2 → KILLED

123

1.1
Location : detail
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:theDetailHasTheOrdersNewestFirstAndTheLastAddress()]
removed conditional - replaced equality check with false → KILLED

2.2
Location : detail
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:theDetailHasTheOrdersNewestFirstAndTheLastAddress()]
replaced return value with null for com/rbctcsworld/ecommerce/customer/CustomerService::detail → KILLED

132

1.1
Location : lambda$setActive$3
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:settingTheSameStateAgainChangesAndRecordsNothing()]
replaced boolean return with false for com/rbctcsworld/ecommerce/customer/CustomerService::lambda$setActive$3 → KILLED

2.2
Location : lambda$setActive$3
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:anAdminOrAnUnknownIdIsNotACustomer()]
replaced boolean return with true for com/rbctcsworld/ecommerce/customer/CustomerService::lambda$setActive$3 → KILLED

133

1.1
Location : lambda$setActive$4
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:anAdminOrAnUnknownIdIsNotACustomer()]
replaced return value with null for com/rbctcsworld/ecommerce/customer/CustomerService::lambda$setActive$4 → KILLED

134

1.1
Location : setActive
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:disablingEndsEverySessionAndIsAudited()]
removed conditional - replaced equality check with false → KILLED

135

1.1
Location : setActive
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:disablingEndsEverySessionAndIsAudited()]
removed call to com/rbctcsworld/ecommerce/auth/AppUser::setActive → KILLED

136

1.1
Location : setActive
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:disablingEndsEverySessionAndIsAudited()]
removed conditional - replaced equality check with false → KILLED

137

1.1
Location : setActive
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:disablingEndsEverySessionAndIsAudited()]
removed call to org/springframework/context/ApplicationEventPublisher::publishEvent → KILLED

138

1.1
Location : setActive
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:disablingEndsEverySessionAndIsAudited()]
removed conditional - replaced equality check with false → KILLED

2.2
Location : setActive
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:enablingIsAuditedAndKeepsSessionsAsTheyAre()]
removed conditional - replaced equality check with false → KILLED

141

1.1
Location : setActive
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:disablingEndsEverySessionAndIsAudited()]
removed call to com/rbctcsworld/ecommerce/auth/UserRepository::flush → KILLED

142

1.1
Location : setActive
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:enablingIsAuditedAndKeepsSessionsAsTheyAre()]
replaced return value with null for com/rbctcsworld/ecommerce/customer/CustomerService::setActive → KILLED

148

1.1
Location : summary
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:anAdminOrAnUnknownIdIsNotACustomer()]
removed conditional - replaced equality check with false → KILLED

149

1.1
Location : summary
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:enablingIsAuditedAndKeepsSessionsAsTheyAre()]
replaced return value with null for com/rbctcsworld/ecommerce/customer/CustomerService::summary → KILLED

154

1.1
Location : likeEscape
Killed by : com.rbctcsworld.ecommerce.customer.CustomerServiceTest.[engine:junit-jupiter]/[class:com.rbctcsworld.ecommerce.customer.CustomerServiceTest]/[method:likeWildcardsAreEscaped()]
replaced return value with "" for com/rbctcsworld/ecommerce/customer/CustomerService::likeEscape → KILLED

Active mutators

Tests examined


Report generated by PIT 1.30.0 support