magendoo / module-customer-segment
Magento 2 dynamic customer segmentation module — rule-based segments with admin UI, REST API, CLI, and Cart Price Rule integration.
Magendoo CustomerSegment for Magento 2
A comprehensive Customer Segmentation module for Magento 2 Community Edition that enables merchants to create dynamic customer segments based on various criteria including customer attributes, order history, shopping cart data, and behavior patterns.
Screenshots
Segment Grid — manage all your customer segments at a glance
[image: Customer Segments Grid]
Segment Editor — visual rule builder with conditions and customer matching
[image: Customer Segment Edit]
Documentation
| Document | Description |
|---|---|
| User Guide | End-user documentation for managing segments |
| Developer Documentation | Technical documentation for developers |
| API Documentation | REST API reference and examples |
| Testing Guide | Unit testing patterns and best practices |
| Testing Lessons | Implementation lessons and bug analysis |
| Changelog | Version history and changes |
Features
Customer Segmentation
- Dynamic Segments: Automatically assign customers based on rules
- Manual Segments: Static customer assignments
- Real-time Updates: Refresh segments on customer events
- Scheduled Updates: Cron-based segment refresh
Condition Types
Customer Attributes
- Email, First Name, Last Name
- Date of Birth, Gender
- Tax/VAT Number
- Website, Store View, Customer Group
- Account Creation Date
Order History
- Total Orders Count
- Total Revenue / Average Order Value
- First/Last Order Date
- Total Items Purchased
- Used Coupon Codes
- Payment/Shipping Methods
- Shipping Countries
- Order Status
Shopping Cart
- Cart Subtotal
- Cart Items Count
- Contains Products (by SKU)
- Has Active Cart
- Days Since Cart Activity
Product Interactions
- Viewed Categories
- Purchased Products (SKU)
- Purchased from Categories
- Wishlist Items Count
Admin Features
- Grid view of all segments with customer counts
- Create/Edit segments with visual rule builder
- Preview matching customers before saving
- "Matched Customers" tab on edit page shows assigned customers
- Refresh button on edit page
- Mass actions (Delete, Refresh)
- Export segment customers (CSV/XML)
API & Integrations
- REST API for segment management
- CLI commands for segment operations
- Integration with Cart Price Rules
- Customer grid segment filtering
- Segment indexer with mview support
Installation
Via Composer (Recommended)
composer require magendoo/module-customer-segment
bin/magento setup:upgrade
bin/magento setup:di:compile
bin/magento setup:static-content:deploy -f
bin/magento cache:flush
Manual Installation
- Extract files to
app/code/Magendoo/CustomerSegment/ - Run the following commands:
bin/magento setup:upgrade
bin/magento setup:di:compile
bin/magento setup:static-content:deploy -f
bin/magento cache:flush
Configuration
Access the configuration at:
Admin → Customers → Customer Segments
Usage
Creating a Segment
- Navigate to Customers → Customer Segments
- Click "Add New Segment"
- Fill in the general information:
- Name (required)
- Description (optional)
- Status (Active/Inactive)
- Refresh Mode (Manual/Cron/Real-time)
- Configure conditions in the Conditions tab
- Save the segment
- Click "Refresh Segment Data" to populate customers
Segment Refresh Modes
| Mode | Description |
|---|---|
| Manual | Admin must click refresh button to update |
| Cron | Updated automatically on cron schedule (default: daily at 2 AM) |
| Real-time | Updated on customer events (login, order, etc.) |
CLI Commands
# Refresh specific segment(s)
bin/magento magendoo:customer-segment:refresh 1
bin/magento magendoo:customer-segment:refresh 1 2 3
# Refresh all active segments
bin/magento magendoo:customer-segment:refresh --all
# Export segment customers
bin/magento magendoo:customer-segment:refresh 1 --export --format=csv
Using Segments in Cart Price Rules
- Go to Marketing → Cart Price Rules
- Create or edit a rule
- In the Conditions section, add condition:
- Customer Segment → is → [Select your segment]
- Save the rule
API Reference
REST API Endpoints
| Method | Endpoint | Description |
|---|---|---|
| GET | /V1/customer-segments |
List all segments |
| GET | /V1/customer-segments/:segmentId |
Get segment by ID |
| POST | /V1/customer-segments |
Create new segment |
| PUT | /V1/customer-segments/:segmentId |
Update segment |
| DELETE | /V1/customer-segments/:segmentId |
Delete segment |
| POST | /V1/customer-segments/:segmentId/refresh |
Refresh segment |
| GET | /V1/customers/:customerId/segments |
Get customer's segments |
Example: Create Segment via API
curl -X POST "https://your-store.com/rest/V1/customer-segments" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN" \
-d '{
"segment": {
"name": "VIP Customers",
"description": "Customers with 10+ orders",
"is_active": true,
"refresh_mode": "cron",
"conditions_serialized": "{...}"
}
}'
Database Structure
Tables
| Table | Description |
|---|---|
magendoo_customer_segment |
Stores segment definitions |
magendoo_customer_segment_customer |
Customer-segment relationships |
magendoo_customer_segment_log |
Segment activity log |
Events
The module dispatches the following events:
| Event | Description |
|---|---|
magendoo_customersegment_segment_save_before |
Before segment save |
magendoo_customersegment_segment_save_after |
After segment save |
magendoo_customersegment_segment_refresh_before |
Before segment refresh |
magendoo_customersegment_segment_refresh_after |
After segment refresh |
magendoo_customersegment_customer_assigned |
Customer assigned to segment |
magendoo_customersegment_customer_removed |
Customer removed from segment |
Extension Points
Adding Custom Conditions
Create a plugin to add custom conditions:
class AddCustomConditionPlugin
{
public function afterGetNewChildSelectOptions($subject, $result)
{
$result[] = [
'label' => __('My Custom Condition'),
'value' => 'Vendor\Module\Model\Condition\MyCondition'
];
return $result;
}
}
Troubleshooting
Segments not refreshing
- Check if the segment is Active
- Verify cron is running:
bin/magento cron:run - Check logs at
var/log/system.log
Customers not matching
- Verify condition logic
- Check that customer data exists
- Test with CLI:
bin/magento magendoo:customer-segment:refresh --all
Performance issues
- Enable batch processing (already enabled by default)
- Use Manual refresh mode for large segments
- Schedule refresh during low-traffic hours
Testing
Running Tests
# Run all module tests
vendor/bin/phpunit --filter Magendoo app/code/Magendoo/CustomerSegment/Test/Unit
# Run specific test class
vendor/bin/phpunit --filter SegmentManagementTest app/code/Magendoo/CustomerSegment/Test/Unit/Model/SegmentManagementTest.php
# Run with coverage
vendor/bin/phpunit --filter Magendoo --coverage-html coverage app/code/Magendoo/CustomerSegment/Test/Unit
Test Coverage
| Component | Tests | Assertions |
|---|---|---|
| SegmentManagement | 31 | 65 |
| Condition\Combine | 10 | 13 |
| Condition\Customer | 21 | 52 |
| Condition\Order | 22 | 40 |
| Condition\Cart | 22 | 38 |
| Total | 106 | 198 |
Security Tested
- ✅ CSV Injection Prevention (fputcsv)
- ✅ Formula Injection Protection
- ✅ Condition Type Allowlist
- ✅ Arbitrary Class Instantiation Prevention
See TESTING.md and TESTING_LESSONS.md for detailed testing documentation.
Support
For support and questions:
- Email: [email protected]
License
This module is licensed under the Open Software License v. 3.0 (OSL-3.0).
See LICENSE.txt for details.
Credits
Developed by Magendoo (https://magendoo.com)
Version: 1.0.1
Compatibility: Magento 2.4.x
PHP Version: 8.1+
Changelog
All notable changes to the Magendoo CustomerSegment module will be documented in this file.
The format is based on Keep a Changelog.
[1.1.0] - 2026-04-03
Added
- Product Interactions condition type (viewed categories, purchased products, purchased categories, wishlist items count) with
betweenoperator - SqlBuilder for batch customer validation (N+1 performance fix)
- Segment indexer with mview support (
etc/indexer.xml,etc/mview.xml) - System configuration admin panel (
etc/adminhtml/system.xml,etc/config.xml) for enable/disable, default refresh mode, cron schedule - RefreshButton on segment edit page
- Matched Customers tab on segment edit page with pagination
- MatchedCustomersDataProvider for matched customers grid
- CustomerSegmentRelation model and ResourceModel for segment-customer relationships
- Product::class added to condition type allowlists (SegmentManagement + NewConditionHtml)
- Cart Price Rule integration now loads segment options from repository (was stub)
- Functional test suite (Playwright) — API, CLI, Admin UI, Integration tests
- Unit tests for Product condition and SqlBuilder
Fixed
- CRITICAL: Segment model extended AbstractModel instead of AbstractExtensibleModel — getExtensionAttributes() crashed all REST API serialization
- CRITICAL: SegmentSearchResultsInterface used short class name in @return docblock — Magento Web API reflection failed with "Class SegmentInterface does not exist" on getList endpoint
- CRITICAL: Edit controller stored full Segment model object in DataPersistor (session) — non-serializable dependencies (FormFactory/ObjectManager/Closures) caused "Serialization of 'Closure' is not allowed" fatal error on every admin page load
- Conditions blocks now load segment from DB via request param instead of DataPersistor
- Removed DataPersistorInterface dependency from Conditions blocks
Changed
- Segment model constructor now accepts ExtensionAttributesFactory and AttributeValueFactory (required by AbstractExtensibleModel)
- Version bumped to 1.1.0
[1.0.1] - 2026-04-01
Added
- Comprehensive Unit Test Suite - 106 tests with 198 assertions
- SegmentManagement tests (31 tests) - CRUD, refresh, export, validation
- Condition tests (75 tests) - Customer, Order, Cart, Combine conditions
- Security-critical tests for CSV injection prevention
- Condition type allowlist verification
- Error handling and edge case coverage
- Testing documentation:
- TESTING.md - Testing patterns and best practices
- TESTING_LESSONS.md - Implementation lessons learned
Fixed
- Security: CSV export now uses fputcsv() to prevent formula injection
- Security: Condition instantiation uses allowlist to prevent arbitrary class loading
- Table prefix support in database queries
- Type mismatches in API methods
- Deprecated class replacements (Zend_Db_Expr, Registry)
Technical
- Reduced test code duplication by 30% through refactoring
- Established testing patterns for future development
- All production code issues resolved (see TESTING_LESSONS.md)
[1.0.0] - 2026-04-01
Added
- Initial release of Magendoo CustomerSegment module
- Customer segmentation with dynamic rules engine
- Three condition types: Customer Attributes, Order History, Shopping Cart
- Admin grid for segment management with filtering and mass actions
- Create, edit, delete, and refresh segments
- Three refresh modes: Manual, Cron, Real-time
- REST API for all segment operations
- CLI command for segment refresh
- Integration with Cart Price Rules
- Event system for extensibility
- Database schema with foreign key constraints
- Multi-condition support with AND/OR logic
- Customer count caching
- Export segment customers (CSV/XML)
- Full ACL support for permissions
- Observer-based real-time updates
- Comprehensive documentation
Features
- Dynamic Segments: Automatically assign customers based on rules
- Visual Rule Builder: Admin UI for building complex conditions
- Batch Processing: Efficient customer matching in batches of 1000
- Scheduled Updates: Cron-based segment refresh (default: daily at 2 AM)
- Event-Driven: Real-time updates on customer events
- API Access: Full REST API coverage
- Extensible: Plugin and event support for custom conditions
Technical
- Magento 2.4.x compatibility
- PHP 8.1+ support
- Service Contracts pattern
- Dependency Injection throughout
- Unit and integration test support
- Playwright functional tests
Future Releases (Planned)
[1.2.0] - TBD
- GraphQL API support
- Segment-based email templates
- Customer grid segment column
- Advanced reporting for segments
[1.3.0] - TBD
- Segment-based CMS content
- Segment comparison tool
- Import/Export segment definitions
- Customer segment history
[2.0.0] - TBD
- Machine learning-based segment suggestions
- Segment-based pricing
- Segment-based shipping methods
- Real-time segment webhooks
Requires 9
| Package | Constraint |
|---|---|
| magento/framework | >=103.0.0 |
| magento/module-backend | >=102.0.0 |
| magento/module-catalog | >=104.0.0 |
| magento/module-customer | >=103.0.0 |
| magento/module-quote | >=101.2.0 |
| magento/module-rule | >=100.4.0 |
| magento/module-sales | >=103.0.0 |
| magento/module-ui | >=101.2.0 |
| php | >=8.1 |
Requires-dev 2
| Package | Constraint |
|---|---|
| phpstan/phpstan | ^1.10 || ^2.0 |
| phpunit/phpunit | ^10.5 |
No QA results yet
QA pipelines haven't run for this version. Compatibility and quality results appear here once the vendor publishes a tagged release that gets ingested.
More from magendoo
View vendorEU Base Price (Grundpreis) display for Magento 2. Shows price per reference unit (kg, litre, m) on product pages, category listings, search results and cart. Compliant with EU Price Indication Directive 98/6/EC and German PAngV.
Shipping Restrictions module
Product labels for Magento 2 - first-class label entities with stable codes, manual assignment via product attribute, rule-computed assignments materialized by an indexer, PLP/PDP badges and GraphQL exposure
EU Omnibus Directive (2019/2161) price tracker for Magento 2. Records price changes with timestamps, computes the lowest prior price in the disclosure window, and displays it on PDP and PLP, with async queue processing for bulk operations.
Turn an existing module into recurring revenue.
If you already maintain a Magento 2 module on GitHub or GitLab, listing it on Packagento takes about five minutes. We mirror your tags, handle distribution signing, and route paid licenses through Stripe Connect, so you can keep shipping the way you already do.