Services
Overview
This document provides an overview of the key service components used within the application, specifically focusing on customer-related services. The service layer plays a critical role in orchestrating business logic, handling customer requests, managing account data, and integrating with external services.
Request Structure
- Namespace: Toolstation\Customers\Services
- Models: Customer, Account, CustomerAddress, CustomerCardRequest
Customer Module Services
The customer module handles the following services.
Key Components:
- Account Services:
- AccountCustomerLimitService.php: Manages customer account limits, ensuring compliance with predefined thresholds.
- AccountService.php: Handles core account operations, including creation, updating, and management of customer accounts.
- Application Services:
- ApplicationData.php: Stores and manages application-specific data required for processing customer-related tasks.
- ApplicationService.php: Coordinates the lifecycle of customer applications, from initiation to completion.
- Customer Services:
- CustomerAddressService.php: Manages customer address data, providing functionality for adding, updating, and retrieving addresses.
- CustomerCardService.php: Handles operations related to customer payment cards, including storage and verification.
- CustomerCardRequestService.php: Facilitates the management of customer card requests and processing.
- CustomerNotesAndIssuesService.php: Allows tracking of customer notes and issues, aiding in better customer support and service management.
- Integration Services:
- DnbClientService.php: Integrates with Dun & Bradstreet (D&B) for customer data validation and business intelligence.
- FreshworksService.php: Provides integration with Freshworks CRM for managing customer interactions.
- HelloSignCustomerSignatureService.php: Manages the HelloSign integration for capturing and processing customer signatures.
- Support and Mock Services:
- MockCustomerSignatureService.php: A mock service used for testing signature functionality without affecting production data.
- OrderData.php: Handles data operations related to customer orders, ensuring smooth order processing and tracking.
- SavedAccountApplicationService.php: Manages saved customer applications, allowing users to resume and complete applications at a later time.
AccountCustomerLimitServices Overview
The AccountCustomerLimitService class provides functionalities to manage customer account spending limits, including calculating current month spending, generating spending statistics, and updating customer spending limits. It interacts with customer data to ensure that spending limits are enforced and maintained across the system.
- Namespace: Toolstation\Customers\Services
- Implements: Toolstation\Contracts\Customers\AccountCustomerLimitService
Method: employeeCurrentMonthSpend:
Calculates the current month's total spend for a given customer using the CalculateCreditSpendQuery.
Method: employeeSpendStats: Generates and returns the spending statistics for the current month for a given customer, including the total amount spent, the remaining balance of their spending limit, and the percentage of the limit that has been used.
Example Output
[
'this_month' => [
'spend' => '500.00',
'remaining_balance' => '1500.00',
'percentage_used' => '25.00'
]
]
Method: updateEmployeeLimits:
Updates or deletes the specified spending limits for a customer. Depending on the provided limits array, it either updates the existing limit, creates a new limit, or deletes the limit if the value is empty (and not zero).
Example Output
$limits = [
'monthly_spend_limit' => 2000,
'order_spend_limit' => 500,
'po_required' => 1,
];
$accountCustomerLimitService->updateEmployeeLimits($account, $customer, $limits);
AccountService Overview
The AccountService class is a critical component in the customer management system, designed to handle various operations related to customer accounts. It interacts with the AccountRepository to perform CRUD (Create, Read, Update, Delete) operations on accounts and their attributes. This service also manages customer assignments within accounts, including adding customers as admins or employees and handling trade credit functionalities. Additionally, it triggers specific events corresponding to these operations, which can be used to notify other parts of the system about changes in account status.
- Namespace: Toolstation\Customers\Services
- Implements: Toolstation\Contracts\Customers\AccountService
Key Functionalities
- Account Creation and Management:
The createAccount method allows for the creation of a new customer account using provided data. Upon successful creation, it logs the event and triggers an AccountCreated event. This function lays the foundation for customer management by generating a new account in the system.
- Trade Credit Management:
The enableTradeCredit and disableTradeCredit methods manage the trade credit status of an account. Trade credit is an essential feature for customers who need to purchase on credit. These methods update the account's attributes to reflect the enabled or disabled state and log the changes. The system also broadcasts these changes through AccountTradeCreditEnabled and AccountTradeCreditDisabled events.
- Customer Assignment:
- The service provides methods to assign customers to an account as either admins or employees. The
addAdminToAccountmethod adds a customer as an admin, granting them elevated privileges within the account. Similarly, theaddEmployeeToAccountmethod assigns a customer as an employee. The service also ensures that an employee is not linked to multiple accounts, enforcing business rules that prevent conflicts in account assignments. - Removal of customers from an account is handled by the
removeCustomerFromAccountmethod. This method detaches a customer from an account, and if successful, triggers aCustomerRemovedFromAccountevent.
- Account Attribute Management:
The updateOrCreateAttribute method serves as a general-purpose function to manage the attributes of an account. This method is used internally by other functions like updateCreditLimit and updateRemainingBalance, which specifically handle updating the credit limit and the remaining balance of an account, respectively. These attributes are crucial for managing the financial aspects of customer accounts, ensuring that credit limits are enforced and tracked accurately.
- Account and Customer Retrieval:
- The service provides various methods for retrieving accounts and associated data.
getAccountByNumberandgetAccountByIdallow for the retrieval of accounts by their number or ID.getAccountsByCustomerIdfetches all accounts linked to a specific customer, which is useful for scenarios where a customer may have multiple accounts. Additionally, methods likegetCustomers,getAdminCustomers, andgetEmployeeCustomersprovide the ability to retrieve customers based on their roles within an account. - The
getAccountOrdersmethod retrieves orders associated with an account, supporting pagination to manage large datasets. This is particularly useful for businesses that need to review the transaction history of an account.
- Direct Debit Mandate Management:
The service includes methods for managing direct debit mandates, a common requirement for automated payments. The storeMandateId method stores a direct debit mandate ID associated with an account, enabling automated payment processes. The removeMandateId method removes this ID, effectively disabling the direct debit setup for the account.
ApplicationData Overview
The ApplicationData class is designed to encapsulate and manage the data associated with a customer's application within a system. This class acts as a centralized repository for accessing various details of an application, such as buyer information, company details, credit limits, and payment information. By providing a set of methods to retrieve specific pieces of data, the class simplifies the process of working with application data and ensures that the data is accessed in a consistent manner across the application.
Key Functionalities
- Data Initialization and Structure:
The constructor of the ApplicationData class accepts an array of application data as an argument. This data is then parsed and organized within the class, ensuring that critical fields like primary_email and additional_email are correctly initialized. If additional_email is not provided, it defaults to an empty string. This initialization ensures that the object is always in a valid state when it is used.
- Accessing Application Information:
- The class provides several methods to retrieve various pieces of information related to the application. Each method is designed to access a specific part of the application data, ensuring that the data can be retrieved easily and reliably. The methods include:
applicationDate(): Returns the application date. If the date is not provided, it defaults to the current date and time.primaryEmail(): Retrieves the primary email associated with the application.additionalEmail(): Retrieves the additional email if provided, otherwise returns an empty string.customerNumber(): Returns the customer number associated with the application.applicationData(): Returns the entire application data array.
- Buyer Information:
- The class includes several methods to access buyer-specific information:
buyerName(): Retrieves the buyer's name.buyerEmail(): Retrieves the buyer's email address.buyerPhone(): Retrieves the buyer's phone number.
- Company Information:
- The class provides methods to access various details related to the company associated with the application:
getCompany(): Returns the entire company data array.getCompanyAddress(): Retrieves the company's address.principalDirector() and secondaryDirector(): Retrieve the details of the principal and secondary directors, respectively.
- Credit and Financial Information:
- The class includes methods for accessing credit-related data:
creditLimit(): Retrieves the credit limit associated with the application.getCredit(): Returns the entire credit data array.- Additionally, the class provides methods to access payment and bank details:
getPaymentDetails(): Retrieves the payment details associated with the application.getBankDetails(): Returns the bank details, which are part of the payment details array.
ApplicationService Overview
The ApplicationService class is a service layer component, responsible for managing and processing customer applications. This class interacts with repositories, handles business logic, and communicates with other services such as email notifications. The service encapsulates the logic for creating, updating, deleting, and retrieving applications, as well as more specific operations like saving progress, approving, or declining an application.
- Namespace: Toolstation\Customers\Services
- Implements: Toolstation\Contracts\Customers\ApplicationService
Key Functionalities
- Dependency Injection:
The ApplicationService class relies on dependency injection for its dependencies, such as ApplicationRepository and CompanySearchRequestInterface. These dependencies are injected via the constructor, which simplifies testing and promotes loose coupling.
- Principle Matching Logic:
The findPrinciple method searches for a matching principle name within a dataset. This method cleans and normalizes names, then creates various name variations to improve the accuracy of the search. It checks these variations against the names in the dataset to find a match. This functionality is essential for verifying the identity of individuals associated with a company.
- Recursive Principle Data Building:
The buildPrincipleDataSet method recursively builds a dataset of company principles, including those from parent companies. It fetches principle data using the CompanySearchRequestInterface and organizes it into a structured array. This method is crucial for gathering comprehensive information about company leadership, which might be needed for compliance or credit checks.
- Application CRUD Operations:
- The service provides several methods for creating, updating, deleting, and retrieving applications:
- getApplications: Retrieves a paginated list of applications based on filters.
- getApplication: Retrieves a specific application by ID.
- create: Creates a new application with the provided data.
- update: Updates an existing application with new data.
- delete: Deletes an application by ID.
- Draft Application Handling:
- The service includes methods specifically for handling draft applications:
- getDraftApplicationForCustomer: Retrieves a draft application for a specific customer based on application type.
- saveProgress: Saves the progress of an application, ensuring that it remains in a draft status. If an application with the same customer ID, type, and draft status already exists, it will be updated; otherwise, a new draft application will be created. This method also logs information about the save operation for auditing purposes.
- Approval and Decline Logic:
- The service handles the approval and decline of applications:
- approve: Sends approval emails to the customer and internal teams if the application type is "Procard".
- decline: Sends a decline email to the customer if the application type is "Procard".
- Validation and Error Handling:
The service includes a checkType method to validate the application type. If the type is not valid or not set, it throws an InvalidApplicationType exception. This validation step prevents invalid data from being processed and ensures that the application type is always correct.
CustomerAddressService Overview
The CustomerAddressService class provides methods for managing customer addresses. This includes retrieving, creating, updating, and deleting addresses, as well as configuring address forms based on country-specific settings.
- Namespace: Toolstation\Customers\Services
- Implements: Toolstation\Contracts\Customers\CustomerAddressService
Key Functionalities
- Dependency Injection:
The CustomerAddressService class uses dependency injection to manage its dependencies, specifically CustomerRepository and CountryService. These dependencies are provided through the constructor, promoting better testability and reducing tight coupling between components.
- Customer Address Retrieval:
getCustomerAddresses: Retrieves a collection of addresses for a specified customer. Addresses are sorted by their start date in descending order. This method is used to fetch and display all addresses associated with a customer.getCustomerAddress: Fetches a specific address of a customer by its ID. This method uses caching to optimize performance and reduce redundant database queries. The address is retrieved from the cache if available; otherwise, it is fetched from the database.
- Address Creation and Update:
createCustomerAddress: Creates a new address for a customer with the provided address data. After creating the address, it triggers the CustomerAddressCreated event to notify other parts of the system about the new address. This method ensures that new addresses are properly recorded and communicated.updateCustomerAddress: Updates an existing address based on its ID and the new address data. It uses the UpdateCustomerAddress command to handle the update process and then triggers the CustomerAddressUpdated event. This method ensures that address updates are processed and broadcasted correctly.
- Address Deletion:
deleteCustomerAddress: Soft deletes an address by setting its end date to the current timestamp. If the address being deleted is the primary address, an exception (CustomerModuleException) is thrown to prevent deletion. After successful deletion, theCustomerAddressDeletedevent is triggered. This method manages the removal of addresses while preventing the deletion of critical addresses.
- Address Retrieval by Attributes:
getAddressByAttributes: Retrieves addresses for a customer that match specific attributes (e.g., house number, road names, town). This method uses a series of conditional queries to filter addresses based on the provided criteria. It helps in locating addresses that match given attributes.
- Customer Address Form Configuration:
createCustomerAddressFormConfig: Generates the configuration for address forms based on the country ID and form type. This method retrieves localization settings and validation rules for address fields, constructing a form configuration that adapts to regional requirements.getCustomerAddressFormRules: Retrieves the validation rules for address forms based on the country ID. This method maps form fields to their validation rules, ensuring that address data meets the required criteria.getCustomerAddressFormMessages: Provides the validation error messages for address forms based on the country ID. It collects messages from the form configuration and formats them for use in validation feedback.
CustomerCardRequestService Overview
The CustomerCardRequestService class is a service layer component designed to manage customer card requests within the Toolstation application. It provides a structured interface for creating, retrieving, and managing card requests, which are essential for handling various types of credit and service cards requested by customers.
- Namespace: Toolstation\Customers\Services
- Implements: Toolstation\Contracts\Customers\CustomerCardServiceContract
- Dependency Injection:
The CustomerCardRequestService class does not explicitly show dependency injection in the provided code snippet. However, it relies on the Customer and CustomerCardRequest models, which interact with the database to perform CRUD operations related to card requests.
- Card Request Creation:
createTradeCreditRequest: Creates a new trade credit card request for a given customer. This method logs the request creation process and uses theCustomerCardRequestmodel to store the request details. The request is associated with the customer's ID and card address, with the type set to a predefined trade credit value.createCustomerCardRequest: Creates a general customer card request with a specified type. It logs the creation process and stores the request details in theCustomerCardRequestmodel. The request is linked to the customer's primary address.
- Incomplete Card Request Retrieval:
getIncompleteCardRequests: Retrieves a collection of incomplete card requests. This method optionally includes related data based on the$withparameter and filters the requests that are marked as incomplete.getIncompleteTradeCreditCardRequests: Retrieves a collection of incomplete trade credit card requests specifically. It optionally includes related data and filters requests by the predefined trade credit type.
- Completing Requests:
completeRequests: Marks a collection of card requests as completed. This method logs the completion process and updates theuccr_completedfield for the specified requests in theCustomerCardRequestmodel. It effectively marks requests as processed or finished.
- Incomplete Card Requests by Customer:
getIncompleteCardRequestsByCustomer: Retrieves incomplete card requests for a specific customer, with an optional type filter. This method allows filtering requests based on their type and retrieves requests that are not yet completed.
CustomerCardService Overview
The CustomerCardService class is a service layer component responsible for managing customer cards within the Toolstation application. It provides methods for creating, disabling, and managing card types, ensuring that customers have appropriate card access and that card-related operations are efficiently handled.
- Namespace: Toolstation\Customers\Services
- Implements: Toolstation\Contracts\Customers\CustomerCardServiceContract
Key Functionalities
- Card Creation:
createCard(array $data): CustomerCard|bool: Creates a new customer card with the given data. It checks if the customer already has an active card of the same type before creating a new one. If an active card exists, it logs an informational message and returns false. Otherwise, it creates a new card with an expiration set to a predefined number of years from the current date.createTradeCreditCard(string $customerId): CustomerCard|bool: Creates a trade credit card for the specified customer. This method utilizes the createCard method with the trade credit card type predefined based on the regional settings.
- Card Management:
disableCustomerCard(Customer $customer, int $type): Disables a specific type of card for the given customer by updating the card's active status to false. This method is used for various card types, including trade credit and pro cards.disableTradeCreditCards(Customer $customer): Disables all trade credit cards for the specified customer. It calls the disableCustomerCard method with the trade credit card type.disableProCardCards(Customer $customer): Disables all pro cards for the specified customer. It calls the disableCustomerCard method with the pro card type.
- Regional Card Types:
regionCardType(): int: Determines the card type based on the regional settings. It returns the appropriate card type integer value for the current region, which can be either trade credit or pro card depending on the region.
CustomerNotesAndIssuesService Overview
Managing customer interactions, issues, and related notes is a critical part of customer service operations. The CustomerNotesAndIssuesService class offers a centralized approach to handle these tasks. It enables the creation and management of notes associated with customers and their orders, and it also supports issue tracking by allowing the creation, update, and closure of customer issues. The service ensures that all notes and issues are appropriately logged, facilitating customer support and issue resolution processes.
- Namespace: Toolstation\Customers\Services
- Implements: Toolstation\Contracts\Customers\CustomerNotesAndIssuesServiceContract
Key Functionalities
- Customer Notes Management:
getCustomerNotes: Retrieves a paginated list of notes associated with a specific customer. This method helps in organizing customer notes and facilitates easy retrieval of historical interactions.getCustomerOrderNotes: Retrieves a paginated list of notes attached to the customer's orders. This is essential for tracking order-specific communications and issues.createCustomerNote: Creates a new note on a customer's account. This method triggers the CustomerNoteCreated event to notify other parts of the system about the new note.updateCustomerNote: Updates an existing note on a customer's account, primarily focusing on updating the note's urgency. The method triggers theCustomerNoteUpdatedevent upon a successful update.updateCustomerNoteUsingTimestamp: Updates a note on a customer's account using the timestamp to identify the note. This method is useful for updating notes based on time-sensitive data and triggers theCustomerNoteUpdatedevent.
- Customer Issues Management:
getCustomerIssues: Retrieves a collection of issues associated with a specific customer. This method is vital for tracking all open or resolved issues related to a customer.createCustomerIssue: Creates a new issue on a customer's account. It triggers theCustomerIssueCreatedevent, which includes details like the collection site and supplier email, to keep the system informed of the new issue.closeCustomerIssue: Closes an issue on a customer's account, requiring a comment for closure. This method throws aCustomerModuleExceptionif an attempt is made to close an already closed issue. Upon successful closure, the CustomerIssueClosed event is triggered.addNoteToCustomerIssue: Adds a comment to an issue on a customer's account, with an optional urgency flag. This method triggers theNoteAddedToCustomerIssueevent to notify the system of the new note.updateNoteOnCustomerIssue: Updates a note on a customer issue, focusing on the urgent property. The method triggers the CustomerIssueNoteUpdated event.updateNoteOnCustomerIssueUsingTimestamp: Updates a note on a customer issue using the timestamp to identify the note, primarily updating the urgent property. It triggers theCustomerIssueNoteUpdatedevent.
CustomerService Overview
The CustomerService class provides a comprehensive suite of methods for managing customer-related operations within the Toolstation application. This service handles various functionalities, including creating, updating, and retrieving customer data, managing customer attributes, handling customer-related events, and interacting with other services like auto printers and sites. It acts as a core component in the customer management module, facilitating seamless integration with other parts of the application.
- Namespace: Toolstation\Customers\Services
- Implements: Toolstation\Contracts\Customers\CustomerServiceContract
Key Functionalities
- Customer Retrieval
getCustomer: Retrieves a customer by ID, optionally loading related entities.getCustomerByUsername: Retrieves a customer by their username, applying specified relationships.getCustomersPaginated: Returns a paginated list of customers, filtered by specified criteria.fetchExistingCustomer: Fetches an existing customer by email or creates a new one if multiple records are found.
- Customer Management
createCustomer: Creates a new customer record, including attributes and addresses.updateCustomer: Updates customer details for a given customer ID.disableCustomer: Disables a customer account by appending a token to their username and email.enableCustomer: Enables a customer account by removing a token from their username and email.
- Customer Attributes
getCustomerAttributes: Retrieves a collection of attributes for a specified customer.createCustomerAttribute: Creates a new attribute for a customer.updateOrCreateCustomerAttribute: Updates an existing customer attribute or creates a new one if it doesn't exist.deleteCustomerAttribute: Deletes a specified attribute from a customer.deleteCustomerAttributeByType: Deletes customer attributes by their type.
- Customer Catalogue Requests
createCustomerCatalogueRequest: Creates a catalogue request for a customer and sends it to the auto-printer if necessary.getCustomersLastCatalogueRequest: Retrieves the date of the last catalogue request made by a customer.
- Contact and Notifications
sendContactUsRequestEmail: Sends a "Contact Us" request email to a customer.sendPasswordResetEmail: Sends a password reset email to a customer.
- Customer Branch Management
setDefaultBranchForCustomer: Sets the default branch for a customer.addFavouriteBranchForCustomer: Adds a site as a favorite branch for a customer.removeFavouriteBranchForCustomer: Removes a site from the customer's favorite branches.
- Trade Interest Registration
registerTradeInterest: Registers a customer's interest in trade credit and handles the logic for whether the notification should be sent again.
DnbClientService Overview
The DnbClientService class is used for interacting with the DnB API to obtain company information, such as key contacts. It handles the complexities of authentication and making API requests, providing a straightforward interface for other components of the system.
- Namespace: Toolstation\Customers\Services
- Implements: Toolstation\Contracts\Customers\CompanySearchRequestInterface
Key Functionalities
- getToken
This method is responsible for obtaining an OAuth access token from the DnB API using the client credentials grant type. The token is required for authenticating all subsequent API requests.
- getCompanyPrinciples
This method retrieves the key contacts (principles) associated with a company based on its DUNS number. The DUNS number is a unique identifier for businesses, used globally to identify and track companies.
FreshWorksService Overview
The FreshworksService class provides methods for managing customer tickets through the Freshworks API, including creating, retrieving, and updating tickets, while handling errors gracefully.
- Namespace: Toolstation\Customers\Services
- Implements: Toolstation\Contracts\Customers\FreshworksServiceContract
Key Functionalities
- createTicket
This method creates a new ticket in the Freshworks API. Method to create a ticket in Freshworks. It accepts a request array and returns either a string (in case of an error) or an array (the response from the API).
- getTicket
Method to retrieve a ticket by its ID. It returns the ticket details or an error message. This method fetches ticket details from the Freshworks API based on the provided ticket ID.
- getCustomerTicketsByUid
Method to retrieve customer tickets by a unique external ID. It returns an array of tickets or an error message. This method fetches customer tickets from the Freshworks API based on the provided unique ID.
- getTicketConversations
Method to retrieve conversations for a specific ticket. It supports pagination via the $page parameter. It returns an array of conversations or an error message. This method fetches ticket conversations from the Freshworks API based on the provided ticket ID.
- createTicketNote
Method to create a note for a ticket. The note is private by default. It accepts a request array and returns either a string (in case of an error) or an array (the response from the API).