Generate comprehensive pull request descriptions that help reviewers understand changes quickly a...
Generates comprehensive pull request descriptions from git diffs and commit history. Use when creating PRs to provide structured documentation including summaries, technical details, testing info, and deployment notes.
/plugin marketplace add CuriousLearner/devkit/plugin install devkit@devkit-marketplaceThis skill inherits all available tools. When active, it can use any tool Claude has access to.
Generate comprehensive pull request descriptions that help reviewers understand changes quickly and improve team collaboration.
You are a pull request documentation expert. When invoked:
Analyze Changes:
Generate PR Description:
Include Checklist:
Add Metadata:
Communication Tips:
# Conventional Commits Style
feat: Add user profile page
fix: Resolve login redirect issue
refactor: Simplify authentication logic
docs: Update API documentation
test: Add integration tests for checkout
chore: Update dependencies
perf: Optimize database queries
style: Fix linting issues
# With Scope
feat(auth): Add OAuth2 provider support
fix(api): Handle null responses correctly
refactor(database): Migrate to connection pooling
# With Ticket Reference
feat: Add export functionality [JIRA-123]
fix: Memory leak in websocket handler (#456)
# Breaking Changes
feat!: Migrate to v2 API endpoints
refactor!: Remove deprecated methods
✅ GOOD Titles:
- feat: Add real-time notification system
- fix: Prevent duplicate order submissions
- refactor: Extract payment processing logic
- perf: Reduce initial page load time by 40%
❌ BAD Titles:
- Update code
- Fix bug
- Changes
- WIP
- asdfasdf
## Summary
This PR adds a comprehensive notification system that allows users to receive real-time updates about order status, messages, and system alerts.
## Motivation
**Problem**: Users currently have no way to receive updates about important events without refreshing the page or checking email. This leads to delayed responses and poor user experience.
**Solution**: Implement a WebSocket-based notification system with persistent storage, allowing users to:
- Receive real-time notifications
- View notification history
- Mark notifications as read
- Configure notification preferences
## Changes
### Added
- WebSocket server for real-time notifications (`src/websocket/`)
- Notification service and database schema (`src/models/Notification.js`)
- Frontend notification component with toast UI
- User notification preferences page
- Email fallback for offline users
### Modified
- Updated `User` model to include notification settings
- Enhanced authentication middleware to support WebSocket connections
- Modified dashboard to display notification bell icon
### Removed
- Old polling-based notification checker (deprecated)
## Technical Details
### Architecture
Client (React) <--WebSocket--> Server (Node.js) <--> Redis Pub/Sub <--> Database
### Key Implementation Decisions
1. **WebSocket vs. Server-Sent Events**: Chose WebSocket for bidirectional communication
2. **Redis Pub/Sub**: Enables horizontal scaling across multiple server instances
3. **Persistent Storage**: MongoDB for notification history (7-day retention)
4. **Email Fallback**: Queue-based email notifications for offline users
### Database Schema
```javascript
{
userId: ObjectId,
type: String, // 'order', 'message', 'system'
title: String,
message: String,
data: Object, // Type-specific payload
read: Boolean,
createdAt: Date,
expiresAt: Date // TTL index for auto-cleanup
}



None - This is a new feature with no breaking changes to existing APIs.
No migration needed. New notifications table will be created automatically via migration:
npm run migrate:latest
.env.example)REDIS_URL=redis://localhost:6379
WEBSOCKET_PORT=3001
NOTIFICATION_RETENTION_DAYS=7
EMAIL_FALLBACK_ENABLED=true
ws (^8.0.0) - WebSocket libraryioredis (^5.0.0) - Redis clientsocket.io-client (^4.0.0) - Frontend WebSocket clientAll new dependencies scanned with npm audit - no vulnerabilities found.
Closes #234 Related to #189, #201
Estimated Review Time: 30-45 minutes
ENABLE_NOTIFICATIONS (default: false)/admin/notifications/stats
### Bug Fix Template
```markdown
## Summary
Fixes a critical bug where users were unable to submit orders when using discount codes that exceeded the order total, resulting in negative final amounts.
## Issue
**Bug Description**: When users applied discount codes worth more than their cart total, the checkout process would fail silently, leaving users unable to complete their purchase.
**Impact**:
- Severity: HIGH
- Affected Users: ~500 users/day
- Revenue Impact: Estimated $2,000/day in lost sales
- First Reported: 2024-01-10
- Browser: All browsers
- Environment: Production only
**Error Message**:
ValidationError: Order total cannot be negative at OrderService.validate (src/services/OrderService.js:45)
## Root Cause
The discount validation logic in `OrderService.calculateTotal()` was checking for negative amounts AFTER applying the discount, but before the minimum order total constraint was applied.
```javascript
// ❌ BEFORE (Buggy Code)
const subtotal = calculateSubtotal(items);
const discountAmount = calculateDiscount(subtotal, discountCode);
const total = subtotal - discountAmount;
if (total < 0) {
throw new ValidationError('Order total cannot be negative');
}
// Minimum order total check never reached
The issue occurred because:
// ✅ AFTER (Fixed Code)
const subtotal = calculateSubtotal(items);
const discountAmount = calculateDiscount(subtotal, discountCode);
// Cap discount at subtotal amount
const cappedDiscount = Math.min(discountAmount, subtotal);
const total = Math.max(subtotal - cappedDiscount, 0);
// Ensure minimum order value if needed
if (total > 0 && total < MINIMUM_ORDER_TOTAL) {
throw new ValidationError(
`Order total must be at least $${MINIMUM_ORDER_TOTAL}`
);
}
Added client-side validation to prevent invalid submissions:
describe('Order Discount Validation', () => {
it('should cap discount at subtotal amount', () => {
const order = { subtotal: 50, discount: 75 };
const total = calculateTotal(order);
expect(total).toBe(0);
});
it('should allow discounts equal to subtotal', () => {
const order = { subtotal: 100, discount: 100 };
const total = calculateTotal(order);
expect(total).toBe(0);
});
it('should apply partial discounts correctly', () => {
const order = { subtotal: 100, discount: 25 };
const total = calculateTotal(order);
expect(total).toBe(75);
});
it('should handle percentage discounts', () => {
const order = { subtotal: 100, discountPercent: 150 };
const total = calculateTotal(order);
expect(total).toBe(0); // Capped at 100%
});
});
src/services/OrderService.js - Fixed discount calculation logicsrc/validators/OrderValidator.js - Added discount amount validationsrc/controllers/OrderController.js - Improved error messagesclient/src/components/Checkout.jsx - Added client-side validationclient/src/utils/priceCalculator.js - Frontend discount previewtests/unit/OrderService.test.js - Discount edge casestests/integration/checkout.test.js - End-to-end checkout flowIf issues detected:
git revert <commit-hash>
npm run deploy:production
Fixes #312 Related to #298 (discount validation improvements)
### Refactoring Template
```markdown
## Summary
Refactors the payment processing module to improve code maintainability, testability, and separation of concerns. No functional changes or breaking changes.
## Motivation
The current payment processing code has become difficult to maintain due to:
- Multiple payment providers mixed in single file (~1,200 lines)
- Tight coupling between business logic and provider APIs
- Difficult to test (requires mocking multiple external services)
- Code duplication across payment methods
- Hard to add new payment providers
**Technical Debt**: This refactoring addresses item #45 in our technical debt register.
## Refactoring Goals
1. **Separation of Concerns**: Extract provider-specific logic
2. **Testability**: Enable mocking and unit testing
3. **Maintainability**: Reduce file size and complexity
4. **Extensibility**: Make adding new providers easier
5. **Type Safety**: Add TypeScript interfaces
## Changes Overview
### Before (Problematic Structure)
src/services/ └── PaymentService.js (1,200 lines) ├── Stripe logic ├── PayPal logic ├── Square logic └── Common logic (mixed)
### After (Improved Structure)
src/services/payment/ ├── PaymentService.js (200 lines) // Orchestration layer ├── PaymentProvider.interface.ts // Provider contract ├── providers/ │ ├── StripeProvider.js (150 lines) │ ├── PayPalProvider.js (180 lines) │ └── SquareProvider.js (160 lines) ├── utils/ │ ├── currencyConverter.js │ └── paymentValidator.js └── tests/ ├── PaymentService.test.js └── providers/ ├── StripeProvider.test.js ├── PayPalProvider.test.js └── SquareProvider.test.js
## Technical Details
### Payment Provider Interface
```typescript
interface PaymentProvider {
// Provider identification
readonly name: string;
readonly supportedCurrencies: string[];
// Core payment operations
createPaymentIntent(amount: number, currency: string, metadata?: object): Promise<PaymentIntent>;
capturePayment(paymentId: string): Promise<PaymentResult>;
refundPayment(paymentId: string, amount?: number): Promise<RefundResult>;
// Customer management
createCustomer(customerData: CustomerData): Promise<Customer>;
attachPaymentMethod(customerId: string, paymentMethodId: string): Promise<void>;
// Webhooks
verifyWebhookSignature(payload: string, signature: string): boolean;
handleWebhookEvent(event: WebhookEvent): Promise<void>;
}
// ✅ AFTER: Clean orchestration
class PaymentService {
constructor() {
this.providers = {
stripe: new StripeProvider(config.stripe),
paypal: new PayPalProvider(config.paypal),
square: new SquareProvider(config.square)
};
}
async processPayment(orderId, paymentMethod, amount, currency) {
const provider = this.getProvider(paymentMethod);
try {
// Business logic
const order = await this.validateOrder(orderId);
const convertedAmount = await this.convertCurrency(amount, currency);
// Delegate to provider
const result = await provider.createPaymentIntent(
convertedAmount,
currency,
{ orderId, customerId: order.customerId }
);
// Store transaction
await this.saveTransaction(orderId, result);
return result;
} catch (error) {
await this.handlePaymentError(error, orderId);
throw error;
}
}
getProvider(method) {
const provider = this.providers[method];
if (!provider) {
throw new Error(`Unsupported payment method: ${method}`);
}
return provider;
}
}
// ✅ Easy to mock providers
describe('PaymentService', () => {
it('should process payment with selected provider', async () => {
const mockProvider = {
createPaymentIntent: jest.fn().mockResolvedValue({ id: '123' })
};
const service = new PaymentService();
service.providers.stripe = mockProvider;
await service.processPayment('order-1', 'stripe', 100, 'USD');
expect(mockProvider.createPaymentIntent).toHaveBeenCalledWith(
100,
'USD',
expect.objectContaining({ orderId: 'order-1' })
);
});
});
| Metric | Before | After | Improvement |
|---|---|---|---|
| Cyclomatic Complexity | 45 | 8 | 82% ↓ |
| Lines of Code (main file) | 1,200 | 200 | 83% ↓ |
| Test Coverage | 45% | 87% | 93% ↑ |
| Number of Files | 1 | 12 | Better organization |
Adding a new payment provider now requires:
// 1. Create new provider class
class NewProvider implements PaymentProvider {
// Implement interface methods
}
// 2. Register in service
this.providers.newprovider = new NewProvider(config);
// That's it! No changes to existing code.
Extensive testing performed:
✅ 100% backwards compatible
All existing API interfaces remain unchanged:
// Old code still works
paymentService.processPayment(orderId, 'stripe', 100, 'USD');
None required - this is purely code reorganization.
Optional: New config structure (old structure still supported):
// New recommended structure
{
payment: {
providers: {
stripe: { apiKey: '...', webhookSecret: '...' },
paypal: { clientId: '...', clientSecret: '...' },
square: { accessToken: '...', locationId: '...' }
}
}
}
No performance regression detected:
| Operation | Before | After | Change |
|---|---|---|---|
| Payment creation | 245ms | 242ms | -1.2% |
| Refund processing | 180ms | 178ms | -1.1% |
| Webhook handling | 95ms | 93ms | -2.1% |
Bundle size impact:
This refactoring enables:
Addresses technical debt item #45 Related to #389 (payment provider abstraction discussion)
Focus Areas for Reviewers:
Estimated Review Time: 45-60 minutes (larger refactor)
## Usage Examples
@pr-template-generator @pr-template-generator --type feature @pr-template-generator --type bugfix @pr-template-generator --type refactor @pr-template-generator --include-screenshots @pr-template-generator --minimal
## PR Description Checklist
### Essential Elements
- [ ] Clear title following conventions
- [ ] Summary of changes (what and why)
- [ ] Type of change (feature, bugfix, refactor, etc.)
- [ ] Testing performed
- [ ] Breaking changes documented
- [ ] Related issues linked
### Context and Motivation
- [ ] Problem statement
- [ ] Why this approach was chosen
- [ ] Alternatives considered
- [ ] Impact on users/system
- [ ] Business value delivered
### Technical Details
- [ ] Architecture changes explained
- [ ] Key implementation decisions documented
- [ ] Database schema changes (if any)
- [ ] API changes (if any)
- [ ] Performance implications
### Testing and Quality
- [ ] Unit test coverage
- [ ] Integration tests
- [ ] Manual testing steps
- [ ] Edge cases considered
- [ ] Regression testing performed
### Documentation
- [ ] Code comments added
- [ ] API docs updated
- [ ] User documentation updated
- [ ] README changes (if needed)
- [ ] Migration guide (if needed)
### Deployment
- [ ] Deployment plan outlined
- [ ] Configuration changes documented
- [ ] Environment variables updated
- [ ] Migration scripts included
- [ ] Rollback plan defined
### Visual Changes
- [ ] Screenshots included
- [ ] Before/after comparisons
- [ ] Mobile screenshots
- [ ] Accessibility tested
- [ ] Browser compatibility verified
### Collaboration
- [ ] Specific reviewers assigned
- [ ] Review focus areas highlighted
- [ ] Questions for reviewers listed
- [ ] Estimated review time provided
- [ ] Related team members tagged
## Best Practices
### Writing Clear Descriptions
**DO**:
- Use bullet points for easy scanning
- Include code examples for complex changes
- Add visual aids (screenshots, diagrams, recordings)
- Explain the "why" not just the "what"
- Be specific about impacts and trade-offs
- Link to relevant documentation
- Call out areas needing extra attention
**DON'T**:
- Use vague descriptions ("updated code", "fixed stuff")
- Assume reviewers have full context
- Skip testing information
- Forget to link related issues
- Ignore breaking changes
- Rush the description
- Use jargon without explanation
### For Reviewers
Help reviewers by:
- Estimating review time
- Highlighting complex areas
- Providing test accounts/data if needed
- Including step-by-step testing guide
- Asking specific questions
- Explaining non-obvious decisions
### For Complex PRs
For large or complex PRs:
- Break into smaller PRs when possible
- Provide architecture diagrams
- Record video walkthrough
- Schedule synchronous review session
- Create detailed testing guide
- Explain migration strategy thoroughly
## Communication Tips
### Tone and Style
- Be clear and concise
- Use active voice
- Be respectful and collaborative
- Acknowledge uncertainty
- Ask for feedback
- Explain trade-offs objectively
### Screenshots and Videos
When to include visuals:
- **Always**: UI/UX changes
- **Recommended**: Complex workflows, architecture changes
- **Optional**: Backend-only changes
Tools for screenshots:
- Chrome DevTools device mode (mobile screenshots)
- Annotated screenshots (use arrows, highlights)
- GIF recordings for interactions (LICEcap, ScreenToGif)
- Video recordings for complex flows (Loom, QuickTime)
### Code Examples
Include code snippets for:
- API usage examples
- Migration steps
- Breaking changes
- Complex logic explanation
- Before/after comparisons
## GitHub-Specific Features
### Using Markdown Features
```markdown
# Syntax highlighting
```javascript
const example = 'code';
| Column 1 | Column 2 |
|---|---|
| Data | Data |
@username for people #123 for issues
Closes #123 Fixes #456 Related to #789
### PR Templates in Repository
Create `.github/pull_request_template.md`:
```markdown
## Description
<!-- Describe your changes -->
## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
## Testing
<!-- Describe testing performed -->
## Checklist
- [ ] Tests added
- [ ] Documentation updated
- [ ] No breaking changes
This skill should be used when the user asks to "create a slash command", "add a command", "write a custom command", "define command arguments", "use command frontmatter", "organize commands", "create command with file references", "interactive command", "use AskUserQuestion in command", or needs guidance on slash command structure, YAML frontmatter fields, dynamic arguments, bash execution in commands, user interaction patterns, or command development best practices for Claude Code.
This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins.
This skill should be used when the user asks to "create a hook", "add a PreToolUse/PostToolUse/Stop hook", "validate tool use", "implement prompt-based hooks", "use ${CLAUDE_PLUGIN_ROOT}", "set up event-driven automation", "block dangerous commands", or mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API.