Compare commits
395 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 54b1de78b8 | |||
| ee5bc56f2d | |||
| df2d091174 | |||
| 4c9a1e9ccb | |||
| 65c2c5e471 | |||
| f6ba9bc1e7 | |||
| 05076c4f1d | |||
| f943b229c0 | |||
| 28671cb012 | |||
| d86d375ce4 | |||
| af15f24de7 | |||
| b757f22b97 | |||
| 31b53557ac | |||
| be27713f6e | |||
| 60dd3e70b1 | |||
| 54967147d7 | |||
| 1a02b4b5f2 | |||
| 76ea9bbb04 | |||
| 62b5306548 | |||
| 01562afd31 | |||
| b7466ebfbd | |||
| 17e3c04f24 | |||
| ba49805689 | |||
| 95ee6644f7 | |||
| a0e18a1dd8 | |||
| 9e0490c328 | |||
| 80275c6417 | |||
| 36c71ecb1e | |||
| c99362a3e5 | |||
| 9331465c26 | |||
| 9d9bcf7847 | |||
| c7fd90c08d | |||
| e35fc6c938 | |||
| f1a3e9f02f | |||
| d0eecbbf79 | |||
| 01d292f5a9 | |||
| b0ce510155 | |||
| 76d13d699a | |||
| be9571353a | |||
| 147200ff8e | |||
| 492a4fc969 | |||
| 5742c92449 | |||
| e846de6012 | |||
| a007295abe | |||
| 5d3e29669b | |||
| ef4cc825bf | |||
| f54c82d682 | |||
| 884169e847 | |||
| f8b32a7d3a | |||
| ffaeb8f37b | |||
| c0e3e901d0 | |||
| 0663479bb8 | |||
| 52728dfc12 | |||
| dbe2252421 | |||
| 8e5eaecf6a | |||
| 47c03a9e18 | |||
| 752ff8b9a9 | |||
| c7197a263c | |||
| 9729909c31 | |||
| 2bab9a61b9 | |||
| 082968ea1c | |||
| 2d7201f063 | |||
| 96f4a6601d | |||
| 48b0e35cd1 | |||
| c89895e039 | |||
| 3cf8fbdfb9 | |||
| d6364dcde1 | |||
| d631646167 | |||
| 2706166f55 | |||
| b584ce43dd | |||
| 6b7f0035ef | |||
| 3e16c1e656 | |||
| e6d6babb38 | |||
| 2476dd3c1b | |||
| 3ec638cbd2 | |||
| c5ec9a0875 | |||
| 3b7e549e02 | |||
| 7fe9f89574 | |||
| c5def50e31 | |||
| c386361881 | |||
| 94f831f7d1 | |||
| 1ba8b6e590 | |||
| 030bdc65ab | |||
| 148262a78e | |||
| 787c38ad82 | |||
| 79d3f2ef3d | |||
| 82c0aeef41 | |||
| 5f17ca51ac | |||
| fdd8247527 | |||
| d1ddd28250 | |||
| 34458df474 | |||
| 467f1cdbf2 | |||
| cd2353b57d | |||
| 17e34a6d5e | |||
| 063436670a | |||
| 2f9f0a0900 | |||
| c44394ea0c | |||
| 3177072e1d | |||
| 71022ad3f1 | |||
| 6d9c1d2464 | |||
| de11da2b06 | |||
| d984165af1 | |||
| 7df4786499 | |||
| 162fe010fe | |||
| 426983ffaa | |||
| 87c5eb6323 | |||
| cb864b18a5 | |||
| 4b4c8d94b9 | |||
| dd0a9ffea6 | |||
| 353b1599b6 | |||
| 97388cf840 | |||
| 8f5a399a25 | |||
| efd3e73aa2 | |||
| 0f1b604554 | |||
| 48d7303963 | |||
| b9e72e6231 | |||
| 80c5f6289a | |||
| 895975482d | |||
| e81cd8ed2c | |||
| bff5faf02b | |||
| 8df5a3fe00 | |||
| 83295a25f3 | |||
| 0fad4305d4 | |||
| 2f60910b09 | |||
| f48d5115ce | |||
| 774763c21c | |||
| c1b690edd3 | |||
| e34b11aca5 | |||
| b4f4f441b5 | |||
| 475e233c2a | |||
| 3e289479f0 | |||
| 0cee520f0d | |||
| c3392bef13 | |||
| 7fed5bc18b | |||
| 43028228c8 | |||
| f1092772fb | |||
| 702c2ff7b5 | |||
| b75f9e3d21 | |||
| 2e26edbb3a | |||
| 643e1a5dcf | |||
| 21f1d7833b | |||
| 9e1a07aad3 | |||
| b2b9a75731 | |||
| 287332eddf | |||
| 8550ba243d | |||
| ad09db606a | |||
| c27539ca29 | |||
| 9b4bff48f0 | |||
| 6c30c248bc | |||
| 9443b5b446 | |||
| 25088e4a33 | |||
| fcd06afcb2 | |||
| 2f55632792 | |||
| 54365015d8 | |||
| 4dd40f609f | |||
| d760036972 | |||
| 0e27844a28 | |||
| d369383c7d | |||
| 54fcc4b094 | |||
| e87b1385cf | |||
| 66ca57f187 | |||
| 430efe624d | |||
| dc6d2dd358 | |||
| 4969363f78 | |||
| 0e3938f845 | |||
| 7f379bd6a2 | |||
| f751ded65b | |||
| 0c8d0fa8d1 | |||
| f7f37fb4e4 | |||
| d484e60c46 | |||
| a6f44e5bb4 | |||
| 363357bff4 | |||
| 843123bbdb | |||
| 1d76d930bd | |||
| cde9478899 | |||
| d080198220 | |||
| 35231d8b96 | |||
| 2e11c452a9 | |||
| 02bff371c1 | |||
| 375c3e2d1f | |||
| 57d6495271 | |||
| 6ca3b0d6fa | |||
| 85a95aa2d0 | |||
| 2501b00079 | |||
| e0a25ff629 | |||
| d2b344ea24 | |||
| 99c7bac99b | |||
| 59d3dd06b6 | |||
| 0f6f38a70e | |||
| 2a2ded7a53 | |||
| cb681dbd68 | |||
| 8ae0ecef25 | |||
| bffdaa9f57 | |||
| 9ef5227f0f | |||
| a250ea605f | |||
| a70d5a4bdb | |||
| ce2333e309 | |||
| 0c9661d694 | |||
| a780959de9 | |||
| 4382de3a79 | |||
| 0a45fcbdfd | |||
| 747caaf3e7 | |||
| 0cf1406314 | |||
| a8257001a7 | |||
| 4616308402 | |||
| 910c2d0e37 | |||
| d4520ff6b0 | |||
| 1b899e024d | |||
| 8170527ee4 | |||
| 3e733969dc | |||
| 39231ef856 | |||
| ca4da6932e | |||
| 16f7f1c340 | |||
| 0718e41cc5 | |||
| 1f77134597 | |||
| 8a2e701ff2 | |||
| 2ef4ac4b9c | |||
| 06a3bd532d | |||
| 544c8f3081 | |||
| ca93cf7652 | |||
| dd5bdedf0a | |||
| 1a553ab287 | |||
| ecfeddb34a | |||
| 1cd47211a5 | |||
| 66320166b8 | |||
| 989ee58481 | |||
| dd1f72bf58 | |||
| 0b6937973c | |||
| 5e804a35f1 | |||
| 3e70f87d88 | |||
| 7e8560ae58 | |||
| ed8ec89bcc | |||
| 868e57ee0c | |||
| 3b59bd499a | |||
| a8e0cc9195 | |||
| 616f1d98a1 | |||
| aab7345590 | |||
| e3ef9d70be | |||
| a03fb99242 | |||
| bca6d55684 | |||
| 5dc95098ea | |||
| e5ec754abc | |||
| ec4069ce38 | |||
| f248e27702 | |||
| 32006a2bda | |||
| 1412d3fefd | |||
| 9fcefa3ab9 | |||
| e6dbbb49a1 | |||
| 789e7dcdb6 | |||
| 3bedf10449 | |||
| 183c719614 | |||
| 36ea9cde04 | |||
| 1e4278ffb2 | |||
| 515acb654c | |||
| 7bc9ded118 | |||
| 30d1a3c756 | |||
| 7e167cf943 | |||
| cb5bb7dbaf | |||
| 942f5364e8 | |||
| fcba06172a | |||
| 947290f1dc | |||
| 14f405a84a | |||
| 781a59cbf6 | |||
| b1765e98f7 | |||
| c2c9210317 | |||
| 07eacdbceb | |||
| ef5da8def8 | |||
| 78bae4addf | |||
| 049eaf0dfc | |||
| 1ab84d8038 | |||
| 83a8d58096 | |||
| 8dbdd5aac0 | |||
| 235b1d4e8c | |||
| b40f2c8ffb | |||
| 63337b418d | |||
| 2ebc776cc9 | |||
| a0691e8857 | |||
| 50fc188f01 | |||
| 14f92d5147 | |||
| 802cda1b34 | |||
| 33d9c43450 | |||
| afcff10892 | |||
| 1a49d7b127 | |||
| a816c2413b | |||
| b22b76f96e | |||
| ea5e475f32 | |||
| 626baa65ec | |||
| bcba3a153c | |||
| 3e389365d5 | |||
| e29f38280e | |||
| 0f4f7161c8 | |||
| b4138bbc82 | |||
| 80c1cfd9e4 | |||
| 37518e6aa2 | |||
| a2b6293566 | |||
| 77cc535ab2 | |||
| 5e73e0cf0f | |||
| 90be402106 | |||
| e9ae43a81b | |||
| 78333da3d5 | |||
| fc7d34a131 | |||
| efc6dbeb0a | |||
| d78a72c286 | |||
| ba12fecc5c | |||
| 74cc4408c7 | |||
| ccf194ed8a | |||
| a2bfeafcea | |||
| f98a3bf109 | |||
| 3981fdcbf3 | |||
| 5234e46d92 | |||
| a3167d5783 | |||
| 7bcfbf6bd4 | |||
| ad2c8f1704 | |||
| 55a34af986 | |||
| 54451d2ea6 | |||
| 9cf0f0c0c7 | |||
| de66b8b316 | |||
| 008c8a3ad0 | |||
| 18603f6881 | |||
| d7aa5efe30 | |||
| 21f5047640 | |||
| a539b08499 | |||
| 05706ef429 | |||
| 35b48c1b0c | |||
| 046c8b6efa | |||
| fc5f58a992 | |||
| b51d5fb31d | |||
| 10b19df1c4 | |||
| df4532d2fd | |||
| d85b9391cc | |||
| 2018959fdc | |||
| ff3979d527 | |||
| 756a8838d6 | |||
| a319e4f98a | |||
| 1313d89525 | |||
| bcce4d9986 | |||
| a718bb951f | |||
| 621498acc9 | |||
| cafa8dfe2d | |||
| 8d9183c3ac | |||
| 0cea2cc320 | |||
| 9b63e27825 | |||
| 0c98524357 | |||
| 431117087f | |||
| 5deff727a4 | |||
| 554b59359c | |||
| 507c4d869a | |||
| f9bedb6aad | |||
| 88eac07116 | |||
| b1e903f31a | |||
| ec6ebc57e0 | |||
| 3b7023809f | |||
| d733ad0a2f | |||
| 2cf7471687 | |||
| 6b4e7441c9 | |||
| a7b207e689 | |||
| 6b2da83851 | |||
| cc3f2e5b13 | |||
| fad1c895a1 | |||
| 1c217fae43 | |||
| 6230c0fa61 | |||
| 7a537105e3 | |||
| 8a7314d198 | |||
| e41844a13b | |||
| 11baaefe21 | |||
| 97a27fdfbf | |||
| d41471c818 | |||
| 3360e6f023 | |||
| 7d84959c15 | |||
| ded07d3a6b | |||
| 608f4b2231 | |||
| 6a64a98fbf | |||
| f29b1b7e50 | |||
| 0d2c64aa8c | |||
| 256acf8781 | |||
| a0b1cfdcae | |||
| 2b04bbd4f8 | |||
| 888b7563cd | |||
| 3a58090db9 | |||
| 23579dd9be | |||
| 7c12b7419c | |||
| f05bb4dde2 | |||
| 703f101c11 | |||
| 30eec9fb7d | |||
| 83a831c46d | |||
| b72780c54e | |||
| 8c9a91be1c | |||
| f892c94feb | |||
| 7b04e7e752 | |||
| 822e5346d8 | |||
| 4bdb996c6c | |||
| 830e7fc3d7 | |||
| c1ecefafc0 | |||
| f467409baf | |||
| c4876410ea |
@@ -0,0 +1,239 @@
|
||||
---
|
||||
allowed-tools: Bash(git diff:*), Bash(git status:*), Bash(git log:*), Bash(git show:*), Bash(git remote show:*), Read, Glob, Grep, LS, Task
|
||||
description: Complete a security review of the pending changes on the current branch
|
||||
---
|
||||
|
||||
You are a senior security engineer conducting a focused security review of the changes on this branch.
|
||||
|
||||
GIT STATUS:
|
||||
|
||||
```
|
||||
!`git status`
|
||||
```
|
||||
|
||||
FILES MODIFIED:
|
||||
|
||||
```
|
||||
!`git diff --name-only origin/HEAD...`
|
||||
```
|
||||
|
||||
COMMITS:
|
||||
|
||||
```
|
||||
!`git log --no-decorate origin/HEAD...`
|
||||
```
|
||||
|
||||
DIFF CONTENT:
|
||||
|
||||
```
|
||||
!`git diff --merge-base origin/HEAD`
|
||||
```
|
||||
|
||||
Review the complete diff above. This contains all code changes in the PR.
|
||||
|
||||
OBJECTIVE:
|
||||
Perform a security-focused code review to identify HIGH-CONFIDENCE security vulnerabilities that could have real exploitation potential. This is not a general code review - focus ONLY on security implications newly added by this PR. Do not comment on existing security concerns.
|
||||
|
||||
CRITICAL INSTRUCTIONS:
|
||||
|
||||
1. MINIMIZE FALSE POSITIVES: Only flag issues where you're >80% confident of actual exploitability
|
||||
2. AVOID NOISE: Skip theoretical issues, style concerns, or low-impact findings
|
||||
3. FOCUS ON IMPACT: Prioritize vulnerabilities that could lead to unauthorized access, data breaches, or system compromise
|
||||
4. EXCLUSIONS: Do NOT report the following issue types:
|
||||
- Denial of Service (DOS) vulnerabilities, even if they allow service disruption
|
||||
- Secrets or sensitive data stored on disk (these are handled by other processes)
|
||||
- Rate limiting or resource exhaustion issues
|
||||
|
||||
SECURITY CATEGORIES TO EXAMINE:
|
||||
|
||||
**Input Validation Vulnerabilities:**
|
||||
|
||||
- SQL injection via unsanitized user input
|
||||
- Command injection in system calls or subprocesses
|
||||
- XXE injection in XML parsing
|
||||
- Template injection in templating engines
|
||||
- NoSQL injection in database queries
|
||||
- Path traversal in file operations
|
||||
|
||||
**Authentication & Authorization Issues:**
|
||||
|
||||
- Authentication bypass logic
|
||||
- Privilege escalation paths
|
||||
- Session management flaws
|
||||
- JWT token vulnerabilities
|
||||
- Authorization logic bypasses
|
||||
|
||||
**Crypto & Secrets Management:**
|
||||
|
||||
- Hardcoded API keys, passwords, or tokens
|
||||
- Weak cryptographic algorithms or implementations
|
||||
- Improper key storage or management
|
||||
- Cryptographic randomness issues
|
||||
- Certificate validation bypasses
|
||||
|
||||
**Injection & Code Execution:**
|
||||
|
||||
- Remote code execution via deseralization
|
||||
- Pickle injection in Python
|
||||
- YAML deserialization vulnerabilities
|
||||
- Eval injection in dynamic code execution
|
||||
- XSS vulnerabilities in web applications (reflected, stored, DOM-based)
|
||||
|
||||
**Data Exposure:**
|
||||
|
||||
- Sensitive data logging or storage
|
||||
- PII handling violations
|
||||
- API endpoint data leakage
|
||||
- Debug information exposure
|
||||
|
||||
Additional notes:
|
||||
|
||||
- Even if something is only exploitable from the local network, it can still be a HIGH severity issue
|
||||
|
||||
ANALYSIS METHODOLOGY:
|
||||
|
||||
Phase 1 - Repository Context Research (Use file search tools):
|
||||
|
||||
- Identify existing security frameworks and libraries in use
|
||||
- Look for established secure coding patterns in the codebase
|
||||
- Examine existing sanitization and validation patterns
|
||||
- Understand the project's security model and threat model
|
||||
|
||||
Phase 2 - Comparative Analysis:
|
||||
|
||||
- Compare new code changes against existing security patterns
|
||||
- Identify deviations from established secure practices
|
||||
- Look for inconsistent security implementations
|
||||
- Flag code that introduces new attack surfaces
|
||||
|
||||
Phase 3 - Vulnerability Assessment:
|
||||
|
||||
- Examine each modified file for security implications
|
||||
- Trace data flow from user inputs to sensitive operations
|
||||
- Look for privilege boundaries being crossed unsafely
|
||||
- Identify injection points and unsafe deserialization
|
||||
|
||||
REQUIRED OUTPUT FORMAT:
|
||||
|
||||
You MUST output your findings in markdown. The markdown output should contain the file, line number, severity, category (e.g. `sql_injection` or `xss`), description, exploit scenario, and fix recommendation.
|
||||
|
||||
For example:
|
||||
|
||||
# Vuln 1: XSS: `foo.py:42`
|
||||
|
||||
- Severity: High
|
||||
- Description: User input from `username` parameter is directly interpolated into HTML without escaping, allowing reflected XSS attacks
|
||||
- Exploit Scenario: Attacker crafts URL like `/bar?q=<script>alert(document.cookie)</script>` to execute JavaScript in victim's browser, enabling session hijacking or data theft
|
||||
- Recommendation: Use Flask's escape() function or Jinja2 templates with auto-escaping enabled for all user inputs rendered in HTML
|
||||
|
||||
SEVERITY GUIDELINES:
|
||||
|
||||
- **HIGH**: Directly exploitable vulnerabilities leading to RCE, data breach, or authentication bypass
|
||||
- **MEDIUM**: Vulnerabilities requiring specific conditions but with significant impact
|
||||
- **LOW**: Defense-in-depth issues or lower-impact vulnerabilities
|
||||
|
||||
CONFIDENCE SCORING:
|
||||
|
||||
- 0.9-1.0: Certain exploit path identified, tested if possible
|
||||
- 0.8-0.9: Clear vulnerability pattern with known exploitation methods
|
||||
- 0.7-0.8: Suspicious pattern requiring specific conditions to exploit
|
||||
- Below 0.7: Don't report (too speculative)
|
||||
|
||||
FINAL REMINDER:
|
||||
Focus on HIGH and MEDIUM findings only. Better to miss some theoretical issues than flood the report with false positives. Each finding should be something a security engineer would confidently raise in a PR review.
|
||||
|
||||
FALSE POSITIVE FILTERING:
|
||||
|
||||
> You do not need to run commands to reproduce the vulnerability, just read the code to determine if it is a real vulnerability. Do not use the bash tool or write to any files.
|
||||
>
|
||||
> HARD EXCLUSIONS - Automatically exclude findings matching these patterns:
|
||||
>
|
||||
> 1. Denial of Service (DOS) vulnerabilities or resource exhaustion attacks.
|
||||
> 2. Secrets or credentials stored on disk if they are otherwise secured.
|
||||
> 3. Rate limiting concerns or service overload scenarios.
|
||||
> 4. Memory consumption or CPU exhaustion issues.
|
||||
> 5. Lack of input validation on non-security-critical fields without proven security impact.
|
||||
> 6. Input sanitization concerns for GitHub Action workflows unless they are clearly triggerable via untrusted input.
|
||||
> 7. A lack of hardening measures. Code is not expected to implement all security best practices, only flag concrete vulnerabilities.
|
||||
> 8. Race conditions or timing attacks that are theoretical rather than practical issues. Only report a race condition if it is concretely problematic.
|
||||
> 9. Vulnerabilities related to outdated third-party libraries. These are managed separately and should not be reported here.
|
||||
> 10. Memory safety issues such as buffer overflows or use-after-free-vulnerabilities are impossible in rust. Do not report memory safety issues in rust or any other memory safe languages.
|
||||
> 11. Files that are only unit tests or only used as part of running tests.
|
||||
> 12. Log spoofing concerns. Outputting un-sanitized user input to logs is not a vulnerability.
|
||||
> 13. SSRF vulnerabilities that only control the path. SSRF is only a concern if it can control the host or protocol.
|
||||
> 14. Including user-controlled content in AI system prompts is not a vulnerability.
|
||||
> 15. Regex injection. Injecting untrusted content into a regex is not a vulnerability.
|
||||
> 16. Regex DOS concerns.
|
||||
> 17. Insecure documentation. Do not report any findings in documentation files such as markdown files.
|
||||
> 18. A lack of audit logs is not a vulnerability.
|
||||
>
|
||||
> PRECEDENTS -
|
||||
>
|
||||
> 1. Logging high value secrets in plaintext is a vulnerability. Logging URLs is assumed to be safe.
|
||||
> 2. UUIDs can be assumed to be unguessable and do not need to be validated.
|
||||
> 3. Environment variables and CLI flags are trusted values. Attackers are generally not able to modify them in a secure environment. Any attack that relies on controlling an environment variable is invalid.
|
||||
> 4. Resource management issues such as memory or file descriptor leaks are not valid.
|
||||
> 5. Subtle or low impact web vulnerabilities such as tabnabbing, XS-Leaks, prototype pollution, and open redirects should not be reported unless they are extremely high confidence.
|
||||
> 6. React and Angular are generally secure against XSS. These frameworks do not need to sanitize or escape user input unless it is using dangerouslySetInnerHTML, bypassSecurityTrustHtml, or similar methods. Do not report XSS vulnerabilities in React or Angular components or tsx files unless they are using unsafe methods.
|
||||
> 7. Most vulnerabilities in github action workflows are not exploitable in practice. Before validating a github action workflow vulnerability ensure it is concrete and has a very specific attack path.
|
||||
> 8. A lack of permission checking or authentication in client-side JS/TS code is not a vulnerability. Client-side code is not trusted and does not need to implement these checks, they are handled on the server-side. The same applies to all flows that send untrusted data to the backend, the backend is responsible for validating and sanitizing all inputs.
|
||||
> 9. Only include MEDIUM findings if they are obvious and concrete issues.
|
||||
> 10. Most vulnerabilities in ipython notebooks (*.ipynb files) are not exploitable in practice. Before validating a notebook vulnerability ensure it is concrete and has a very specific attack path where untrusted input can trigger the vulnerability.
|
||||
> 11. Logging non-PII data is not a vulnerability even if the data may be sensitive. Only report logging vulnerabilities if they expose sensitive information such as secrets, passwords, or personally identifiable information (PII).
|
||||
> 12. Command injection vulnerabilities in shell scripts are generally not exploitable in practice since shell scripts generally do not run with untrusted user input. Only report command injection vulnerabilities in shell scripts if they are concrete and have a very specific attack path for untrusted input.
|
||||
>
|
||||
> SIGNAL QUALITY CRITERIA - For remaining findings, assess:
|
||||
>
|
||||
> 1. Is there a concrete, exploitable vulnerability with a clear attack path?
|
||||
> 2. Does this represent a real security risk vs theoretical best practice?
|
||||
> 3. Are there specific code locations and reproduction steps?
|
||||
> 4. Would this finding be actionable for a security team?
|
||||
>
|
||||
> For each finding, assign a confidence score from 1-10:
|
||||
>
|
||||
> - 1-3: Low confidence, likely false positive or noise
|
||||
> - 4-6: Medium confidence, needs investigation
|
||||
> - 7-10: High confidence, likely true vulnerability
|
||||
|
||||
PROJECT FALSE-POSITIVE GUIDANCE (Лидерра):
|
||||
|
||||
> This section is project-specific (Лидерра CRM — Laravel 13 + Vue 3 multi-tenant SaaS).
|
||||
> Apply it alongside the HARD EXCLUSIONS and PRECEDENTS above when filtering findings.
|
||||
>
|
||||
> EXPECTED — treat as NOT a finding:
|
||||
>
|
||||
> 1. Missing application-layer tenant checks where the table has PostgreSQL Row-Level
|
||||
> Security. Tenant isolation is enforced at the DB layer (`SET LOCAL
|
||||
> app.current_tenant_id` via the `SetTenantContext` middleware; 5 DB roles; 39 RLS
|
||||
> policies — see `docs/adr/ADR-002-multitenancy-postgres-rls.md`). DO still flag
|
||||
> queued jobs or code running as the `crm_supplier_worker` role (which is BYPASSRLS)
|
||||
> that read/write tenant-scoped tables WITHOUT an explicit `where('tenant_id', ...)`.
|
||||
> 2. The `tools/*.mjs` economy / ruflo hook scripts using `child_process.spawnSync`
|
||||
> or `process.env`. These are intentional local CLI hooks, not user-facing or
|
||||
> network-reachable code paths.
|
||||
> 3. Hardcoded-secret findings already covered by gitleaks (pre-commit + pre-push).
|
||||
> Do NOT re-report unless a NEW hardcoded credential is introduced by this diff.
|
||||
> 4. Test factories / seeders (`*Factory.php`, `*Seeder.php`) using `Faker` or
|
||||
> predictable values — test-only, per HARD EXCLUSION 11.
|
||||
>
|
||||
> PRIORITISE for this project:
|
||||
>
|
||||
> 1. HMAC / signature verification gaps on inbound webhooks (supplier lead intake).
|
||||
> 2. Signed-URL generation and validation (report file downloads, e.g. the reports
|
||||
> `/api/reports/jobs/{id}/file` endpoint).
|
||||
> 3. `auth:sanctum` + tenant middleware coverage on `/api/*` routes — a missing guard
|
||||
> is a cross-tenant data-leak vector (cf. the J1 / CTO-18 fix).
|
||||
> 4. Personal-data (ПДн) handling under 152-ФЗ — exposure of subject data in
|
||||
> responses, logs, or exports.
|
||||
> 5. Mass-assignment on Eloquent models (`$fillable` / `$guarded` gaps) reachable
|
||||
> from a request.
|
||||
|
||||
START ANALYSIS:
|
||||
|
||||
Begin your analysis now. Do this in 3 steps:
|
||||
|
||||
1. Use a sub-task to identify vulnerabilities. Use the repository exploration tools to understand the codebase context, then analyze the PR changes for security implications. In the prompt for this sub-task, include all of the above.
|
||||
2. Then for each vulnerability identified by the above sub-task, create a new sub-task to filter out false-positives. Launch these sub-tasks as parallel sub-tasks. In the prompt for these sub-tasks, include everything in the "FALSE POSITIVE FILTERING" instructions (including the "PROJECT FALSE-POSITIVE GUIDANCE (Лидерра)" block).
|
||||
3. Filter out any vulnerabilities where the sub-task reported a confidence less than 8.
|
||||
|
||||
Your final reply must contain the markdown report and nothing else.
|
||||
@@ -0,0 +1 @@
|
||||
# CCPM epic/task store — see docs/projects/README.md
|
||||
@@ -0,0 +1 @@
|
||||
# CCPM PRD store — see docs/projects/README.md
|
||||
+20
-18
@@ -37,24 +37,6 @@
|
||||
]
|
||||
},
|
||||
"hooks": {
|
||||
"UserPromptSubmit": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "node \"C:/моя/проекты/портал crm/Документация/tools/ruflo-recall-hook.mjs\""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "node \"C:/моя/проекты/портал crm/Документация/tools/ruflo-queen-hook.mjs\""
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
@@ -64,6 +46,15 @@
|
||||
"command": "node -e \"const f=process.env.CLAUDE_FILE_PATH||''; const pd=process.env.CLAUDE_PROJECT_DIR||''; const path=require('path'); if (f && pd && path.resolve(f) === path.resolve(pd, 'CLAUDE.md')) { process.stderr.write('\\n[hook] WARNING: Direct edit of root CLAUDE.md detected. Per CLAUDE.md §5 п.10, prefer /claude-md-management:revise-claude-md or /claude-md-management:claude-md-improver. If invoked via that skill, this warning is informational.\\n'); }\""
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"matcher": "Task",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "node \"C:/моя/проекты/портал crm/Документация/tools/subagent-prompt-prefix.mjs\""
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PostToolUse": [
|
||||
@@ -85,6 +76,17 @@
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"Stop": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "node tools/observer-stop-hook.mjs",
|
||||
"timeout": 5
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
---
|
||||
name: audit-portal
|
||||
description: Запускать при полном аудите портала Лидерры — периодической сквозной проверке качества и безопасности (статанализ, тесты, схема БД, security, UI-smoke, a11y, coverage, bundle, pre-prod). Триггеры — «провести аудит портала», «полный аудит», «portal audit», подготовка к pre-prod или релизу.
|
||||
---
|
||||
|
||||
# Audit Portal — 14-фазный аудит портала
|
||||
|
||||
## Когда использовать
|
||||
|
||||
Периодический сквозной аудит всего портала Лидерры. Прецеденты — аудиты #1
|
||||
(2026-05-12), #2 (2026-05-13), #3 (2026-05-14). НЕ для точечной проверки одного
|
||||
файла или фичи — для этого прямой инструмент (`/regression`, `/security-review`,
|
||||
Pest).
|
||||
|
||||
## 14 фаз
|
||||
|
||||
Фазы последовательны; фаза 2 — 4 параллельных субагента. Каждая фаза пишет
|
||||
находки в `docs/superpowers/audits/<дата>-portal-full-audit-findings.md`, секция
|
||||
`## Phase N`. BLOCKED-пункты — в `<дата>-portal-full-audit-blocked.md`.
|
||||
|
||||
| # | Фаза | Инструмент |
|
||||
|---|---|---|
|
||||
| 1 | Pre-flight — ветка/HEAD, delta-коммиты, `composer`/`npm install`, skeleton-файлы аудита | git, composer, npm |
|
||||
| 2 | Статанализ — ×4 параллельных субагента | A backend: pint+stan+composer audit · B frontend: eslint+vue-tsc+prettier+knip · C docs: markdownlint+cspell+lychee · D SQL: squawk+pgFormatter |
|
||||
| 3 | Тестовые своды | Pest --parallel + sequential, Vitest, Histoire build, Vite build |
|
||||
| 4 | Целостность схемы — root tables, RLS-политики (инвариант 39), 5 user-функций поимённо, orphan-FK, header drift | Laravel Boost MCP (`database-query`) |
|
||||
| 5 | Security — перечислить CI-workflows ПЕРВЫМ, gitleaks delta + полная история + no-git | gitleaks, `ls .github/workflows/`, `/security-review` + Trail of Bits плагины |
|
||||
| 6 | UI-smoke — обход 24 маршрутов: рендер, 0 JS-ошибок, иконки | Playwright MCP |
|
||||
| 7 | Кросс-док целостность — версии нормативки, schema-маркер, `routes/web.php`, `.mcp.json` | Read, Grep, Select-String |
|
||||
| 8 | A11y — Pa11y на 4 guest-URL + axe-core на auth-views | Pa11y, axe-core через Playwright |
|
||||
| 9 | Coverage — Vitest --coverage, сверка с baseline | `@vitest/coverage-v8` |
|
||||
| 10 | Bundle — Vite build + анализ чанков vs baseline | `parse-bundle-analyze.mjs` |
|
||||
| 11 | Pre-prod + TODO-sweep — schedule, RUNBOOK, `.env.example` diff, Sentry SDK, TODO/FIXME | `artisan schedule:list`, `composer show`, Select-String |
|
||||
| 12 | Категоризация + fix-loop — rollup P0–P3; P0/P1 чинятся через TDD (failing test → fix → `test:parallel`) | Pest, Vitest, git |
|
||||
| 13 | Финальная регрессия | Pest --parallel, Vitest, Vite build, gitleaks, lychee |
|
||||
| 14 | Report + memory + push | Write, `git push` (pre-push: gitleaks-full-history + lychee) |
|
||||
|
||||
Нумерация — Audit #3 (самый свежий). Audit #2 использовал Phase 0–14 с иным
|
||||
порядком a11y / coverage / bundle; при расхождении — версия выше.
|
||||
|
||||
## Рубрика серьёзности
|
||||
|
||||
- **P0** — блокирует production / data corruption / security incident.
|
||||
- **P1** — нарушение функциональности / failing test / type error / a11y violation.
|
||||
- **P2** — warning / style / dead code / stale doc.
|
||||
- **P3** — cosmetic / nice-to-have.
|
||||
|
||||
Fix-eligibility: `[FIX-NOW]` — P0/P1, ≤30 мин, atomic-коммит на находку;
|
||||
`[FIX-DEFER]` — P2/P3, только запись в findings, без кода; `[BLOCKED]` — нужно
|
||||
явное «закрываем» от заказчика → `blocked.md` (категории Q.HARD / Q.PRODUCT /
|
||||
Q.DEFER / Q.INFO).
|
||||
|
||||
## Методология
|
||||
|
||||
- Каждая фаза завершается `git commit` находок. После каждых 3 коммитов —
|
||||
self-review §8 (метрики схемы, версии нормативки).
|
||||
- Регрессия в фазе 12/13 → `systematic-debugging` (≥3 гипотезы) → rollback или
|
||||
forward-fix → перепрогон фазы.
|
||||
- Hard-stop'ы decision-tree: не менять `db/schema.sql`, не закрывать
|
||||
Б-/CTO-/Ю-/Диз-/DO-/OPEN- без явного «закрываем», не ставить пакеты, не
|
||||
править корневой `CLAUDE.md` напрямую, не делать force-push.
|
||||
- BLOCKED-находка, требующая решения владельца → в реестр `Открытые_вопросы`
|
||||
через скил `q-item-add`.
|
||||
|
||||
## Не использовать когда
|
||||
|
||||
- Нужна одна проверка (тест / lint / security одного диффа) — прямой инструмент
|
||||
или `/regression quick`.
|
||||
- Точечный security-review диффа ветки — `/security-review` напрямую.
|
||||
@@ -0,0 +1,43 @@
|
||||
---
|
||||
name: billing-audit
|
||||
description: Аудит денежной корректности биллинг-кода Лидерры — money-инварианты при правке/ревью списаний, тарифов и баланса. Используй при «проверь списание», «аудит биллинга», «не теряются ли копейки», «идемпотентно ли списание», «корректна ли тарифная ступень», «что значит дрейф CsvReconcile», «провенанс charge_source». НЕ для моделирования процесса (process-modeling), поиска узких мест (process-analysis), security-аудита (D3), РСБУ/налогов (ru-tax-accounting), метрик выручки (product-management).
|
||||
---
|
||||
|
||||
# Billing Audit — аудит денежной корректности биллинга Лидерры
|
||||
|
||||
Проектный скил раздела C6 карты «Финансы — биллинг и тарификация». Проверяет
|
||||
**денежные инварианты** биллинг-подсистемы при правке или ревью кода. Объект —
|
||||
корректность *начисления* (не процесс, не безопасность, не учёт/налоги).
|
||||
|
||||
## Когда использовать
|
||||
|
||||
- Правка/ревью кода в `app/app/Services/Billing/**`, `app/app/Jobs/Supplier/CsvReconcileJob.php`,
|
||||
моделей `PricingTier`/`LeadCharge`, контроллеров биллинга.
|
||||
- Вопрос «безопасно ли это денежно?» по списанию, тарифу, балансу, сверке.
|
||||
|
||||
## Процедура аудита (5 инвариантов)
|
||||
|
||||
Полный чек-лист с проверками и ссылками на файлы — `references/invariants.md`.
|
||||
|
||||
1. **Сохранение суммы** — все денежные операции через `bcmath` (bcadd/bcsub/bcmul/bcdiv,
|
||||
scale фиксирован), никаких float; prepaid→₽ конвертация без потери копеек.
|
||||
2. **Идемпотентность списания** — один лид = одно списание; повтор/ретрай джоба
|
||||
не дублирует начисление (проверить уникальный ключ / advisory-lock / upsert).
|
||||
3. **Корректность тарифной ступени** — `PricingTierResolver` выбирает верную из 7
|
||||
ступеней по объёму; границы ступеней (включительно/исключительно) однозначны.
|
||||
4. **Дрейф сверки** — `CsvReconcileJob` порог >5%: что сравнивается, что значит дрейф,
|
||||
куда смотреть (рассинхрон поставки vs ошибка тарифа).
|
||||
5. **Провенанс charge_source** — каждое списание имеет прослеживаемый источник
|
||||
(`charge_source`); ручные/авто/CSV-восстановленные различимы.
|
||||
|
||||
## Границы
|
||||
|
||||
- ≠ `process-modeling` #52 / `process-analysis` #53 — те про *поток/процесс*; billing-audit про *деньги в коде*.
|
||||
- ≠ D3 audit-security (#39/#40) — те про *безопасность*; billing-audit про *денежную корректность*.
|
||||
- ≠ `ru-tax-accounting` #63 — тот про *учёт/налоги* (выход биллинга → налоговая база); billing-audit про *начисление*.
|
||||
- ≠ `product-management:metrics-review` #42 — тот про *метрики выручки*; billing-audit про *корректность*.
|
||||
|
||||
## Связано
|
||||
|
||||
- Reuse: Boost #10 (модели), Pest #18 (тесты инвариантов), Larastan #12 (bcmath/без float), Sentry #34 / Redis #35 (runtime/очередь).
|
||||
- ADR-012 (граница finance-tooling C6/C7).
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"skill": "billing-audit",
|
||||
"positive": [
|
||||
"проверь корректность списания за лид",
|
||||
"аудит денежной логики биллинга",
|
||||
"не теряются ли копейки в prepaid→рублёвом балансе",
|
||||
"идемпотентно ли списание при ретрае",
|
||||
"правильно ли резолвится тарифная ступень",
|
||||
"что значит дрейф >5% в CsvReconcile",
|
||||
"проверь провенанс charge_source",
|
||||
"ревью PricingTierResolver на ошибки округления",
|
||||
"ledger двойной баланс — где может утечь сумма",
|
||||
"audit charge invariants before merge"
|
||||
],
|
||||
"near_miss": [
|
||||
{"prompt": "смоделируй BPMN процесса списания", "expect": "process-modeling #52"},
|
||||
{"prompt": "где узкое место в воронке оплат", "expect": "process-analysis #53"},
|
||||
{"prompt": "security-аудит платёжного эндпоинта", "expect": "D3 audit-security / Semgrep"},
|
||||
{"prompt": "посчитай РСБУ-проводки по выручке", "expect": "ru-tax-accounting #63"},
|
||||
{"prompt": "метрика MRR за месяц", "expect": "product-management metrics-review #42"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
# Денежные инварианты биллинга Лидерры — чек-лист аудита
|
||||
|
||||
Объект-файлы (на момент 20.05.2026):
|
||||
|
||||
- `app/app/Services/Billing/PricingTierResolver.php` — резолюция 7 ступеней (pure).
|
||||
- `app/app/Services/Billing/LedgerService.php` — двойной баланс prepaid→₽ (bcmath).
|
||||
- `app/app/Services/Billing/BillingTopupService.php` — пополнение.
|
||||
- `app/app/Services/Billing/ChargeResult.php` — DTO результата списания.
|
||||
- `app/app/Models/PricingTier.php`, `app/app/Models/LeadCharge.php`.
|
||||
- `app/app/Repositories/PricingTierRepository.php`.
|
||||
- `app/app/Jobs/Supplier/CsvReconcileJob.php` — hourly сверка, алерт дрейфа >5%.
|
||||
- `app/app/Http/Controllers/Api/{AdminPricingTiersController,AdminBillingController,BillingController,TenantChargesController}.php`.
|
||||
|
||||
## I1. Сохранение суммы (bcmath, без float)
|
||||
|
||||
- [ ] Все арифметические операции с деньгами — `bcadd`/`bcsub`/`bcmul`/`bcdiv`/`bccomp` с явным `scale`.
|
||||
- [ ] Нет `+`/`-`/`*`/`/` над денежными значениями (Larastan/grep на float-арифметику в Billing).
|
||||
- [ ] prepaid→₽: конвертация округляет детерминированно (TRUNC/округление вниз в пользу tenant — свериться с кодом), сумма prepaid + ₽ не «исчезает».
|
||||
- [ ] Денежные колонки — целочисленные копейки или DECIMAL, не float/double.
|
||||
|
||||
## I2. Идемпотентность списания
|
||||
|
||||
- [ ] Один лид → одно списание: уникальность по (lead_id) или advisory-lock в `LedgerService`.
|
||||
- [ ] Ретрай `ImportLeadsJob`/`CsvReconcileJob` не создаёт дубль `lead_charges`.
|
||||
- [ ] Транзакция + `lockForUpdate` на балансе при мутации (TOCTOU — см. Sprint 3 lockForUpdate).
|
||||
|
||||
## I3. Корректность тарифной ступени
|
||||
|
||||
- [ ] `PricingTierResolver` выбирает ступень по объёму `delivered_in_month` верно на границах.
|
||||
- [ ] Границы ступеней непрерывны (нет дыр/перекрытий между 7 ступенями).
|
||||
- [ ] Pest покрывает граничные значения (ступень N → N+1).
|
||||
|
||||
## I4. Дрейф сверки CsvReconcile
|
||||
|
||||
- [ ] Порог >5% — что сравнивается (поставка поставщика vs начислено) → `supplier_csv_reconcile_log`.
|
||||
- [ ] Дрейф = рассинхрон поставки (норм) ИЛИ ошибка тарифа (баг) — различить по `charge_source`.
|
||||
|
||||
## I5. Провенанс charge_source
|
||||
|
||||
- [ ] Каждое `lead_charges.charge_source` заполнено и прослеживаемо.
|
||||
- [ ] Авто/ручное/CSV-восстановленное (`recovered_from_csv_at`) различимы.
|
||||
|
||||
## Reuse-инструменты
|
||||
|
||||
Boost #10 (Eloquent-introspection), Pest #18 + pest-parallel-debugger (тесты + race),
|
||||
Larastan #12 (статанализ bcmath), Sentry MCP #34 (runtime списаний), Redis MCP #35 (очередь сверки), context7 #60 (доки bcmath).
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
name: brain-retro
|
||||
description: Use ONCE PER SPRINT (or by explicit user invocation "брейн-ретро") to aggregate evidence from docs/observer/episodes-*.jsonl + notes/*.md and propose regulatory candidates. Read-only — never edits Tooling/Pravila/PSR_v1 automatically; only proposes.
|
||||
---
|
||||
|
||||
# Brain Retro
|
||||
|
||||
Aggregator over observer evidence. Reads JSONL + optional MD notes, surfaces candidates for normative updates. User decides what to apply.
|
||||
|
||||
## When to invoke
|
||||
|
||||
- Explicit user request: «брейн-ретро» / «сделай brain-retro» / `/brain-retro`.
|
||||
- Periodic — owner discretion (e.g. end of sprint).
|
||||
- NOT auto-invoked.
|
||||
|
||||
## What it does NOT do
|
||||
|
||||
- Does NOT edit `docs/Tooling_v8_3.md`, `docs/Pravila_raboty_Claude_v1_1.md`, `docs/Plugin_stack_rules_v1.md`, `CLAUDE.md`, or any normative file.
|
||||
- Does NOT write to `docs/observer/episodes-*.jsonl` (read-only).
|
||||
- Does NOT trigger automatic memory updates.
|
||||
|
||||
## Procedure
|
||||
|
||||
1. **Determine period**: ask user «за какой период» or default to «since last brain-retro» (find latest `docs/observer/notes/YYYY-MM-DD-brain-retro-*.md`).
|
||||
2. **Read evidence**: glob `docs/observer/episodes-YYYY-MM.jsonl` for the period; read all lines as JSON.
|
||||
3. **Read optional notes**: glob `docs/observer/notes/*.md` filtered by date.
|
||||
4. **Update read-counter**: run `node tools/observer-of-observer.mjs record`. This atomically bumps `docs/observer/.read-counter.json` `last_read_at` to now and increments `read_count_last_period`. (Side-effect — used by C3 observer-of-observer for 54-week self-prune detection.)
|
||||
5. **Run the deterministic analyzer**: `node tools/brain-retro-analyzer.mjs docs/observer/episodes-YYYY-MM.jsonl` (pass every monthly file in the period). It returns JSON with `episodeCount`, `observerErrorCount`, `tasks` (episodes grouped into tasks), `causalChains` (error→fix candidates) and `factorMatrix` (outcome distribution per factor). The analyzer deduplicates the routing-gate double-write and infers the true `outcome` of each episode from the next episode's `prompt_signal` — never trust the stored `outcome` (it is `unknown` at write time).
|
||||
6. **Aggregate** per `references/aggregation-template.md` — fill the Factor analysis matrix from the analyzer's `factorMatrix`, the task groups from `tasks`, the causal-chain candidates from `causalChains`.
|
||||
7. **Propose candidates** — clearly separated section «Candidates for owner review». Each candidate has rationale + suggested edit + rejection-option.
|
||||
8. **Save retro note**: `docs/observer/notes/YYYY-MM-DD-brain-retro.md` with full aggregation.
|
||||
8a. **Refresh STATUS.md**: `node tools/status-md-generator.mjs` — auto-rebuild dashboard so it reflects the just-finished retro (`Last /brain-retro: 0 day(s) ago`, current episode count, refreshed C1–C5 controller statuses). Without this, STATUS.md only updates on the next git commit.
|
||||
9. **Report to user**: high-signal summary.
|
||||
|
||||
## Output anatomy
|
||||
|
||||
See `references/aggregation-template.md`.
|
||||
|
||||
## Behavioral rule reminders
|
||||
|
||||
- **«Не использован ≠ проблема»** — when reporting node usage counts, NEVER mark unused nodes as «zombie» / «removal candidate». Cite `memory/feedback_brain_unused_tools_not_problem.md`.
|
||||
- **No auto-edit** — every regulatory suggestion is a candidate, not an action.
|
||||
@@ -0,0 +1,116 @@
|
||||
# Brain-retro aggregation template
|
||||
|
||||
## Period
|
||||
|
||||
YYYY-MM-DD .. YYYY-MM-DD ({N} sessions)
|
||||
|
||||
## Path-type distribution
|
||||
|
||||
| path_type | count | % |
|
||||
|---|---|---|
|
||||
| regulated | A | x% |
|
||||
| improvised | B | y% |
|
||||
| alternative | C | z% |
|
||||
| mixed | D | w% |
|
||||
|
||||
## Outcome distribution
|
||||
|
||||
| outcome | count |
|
||||
|---|---|
|
||||
| success | M |
|
||||
| partial | N |
|
||||
| failure | O |
|
||||
| aborted | P |
|
||||
|
||||
## Top nodes used (from `skill_invoked` events)
|
||||
|
||||
| node | times used | first / last |
|
||||
|---|---|---|
|
||||
|
||||
## Factor analysis matrix (v2 — from `tools/brain-retro-analyzer.mjs`)
|
||||
|
||||
Outcome distribution per factor value. Source: the analyzer’s `factorMatrix`.
|
||||
Outcome is the *inferred* outcome (next-prompt sentiment), not the stored
|
||||
`unknown`. The factor `decision_provenance` directly answers the owner’s
|
||||
question — "is the rework mine or the router’s?"
|
||||
|
||||
For each factor below, render a table: factor value × outcome counts
|
||||
(`success` / `partial` / `rework` / `unknown`).
|
||||
|
||||
### decision_provenance (autonomous vs user_directed_method)
|
||||
|
||||
| provenance | success | partial | rework | unknown |
|
||||
|---|---|---|---|---|
|
||||
|
||||
### economy_level
|
||||
|
||||
| economy_level | success | partial | rework | unknown |
|
||||
|---|---|---|---|---|
|
||||
|
||||
### model · post_compaction · task_size bucket
|
||||
|
||||
(one table each — same columns)
|
||||
|
||||
### node_chosen · task_classification
|
||||
|
||||
(one table each — same columns)
|
||||
|
||||
## Episodes → tasks (from analyzer `tasks`)
|
||||
|
||||
| task_ref | episodes | turns that are rework |
|
||||
|---|---|---|
|
||||
|
||||
## Causal-chain candidates (from analyzer `causalChains`)
|
||||
|
||||
| from (errored episode) | to (later episode) | shared files |
|
||||
|---|---|---|
|
||||
|
||||
## Observer health
|
||||
|
||||
- `observerErrorCount` from the analyzer — observer_error markers in the period.
|
||||
Non-zero = the observer failed silently somewhere; investigate.
|
||||
|
||||
## Canonical chains L1–L13+ hit rate (from analyzer `factorMatrix.chain_ref`)
|
||||
|
||||
| chain | times | outcome split | notes |
|
||||
|---|---|---|---|
|
||||
|
||||
Each node may belong to several L (a multi-chain episode is counted in each).
|
||||
`null` = episodes outside any chain (`direct` + nodes not in L1–L13+) — **not a
|
||||
problem** per `memory/feedback_brain_unused_tools_not_problem`.
|
||||
|
||||
## Improvised chains (path_type=improvised, repeated ≥2)
|
||||
|
||||
| node-set | times | candidate L13+? |
|
||||
|---|---|---|
|
||||
|
||||
## chain_divergence cases
|
||||
|
||||
| canonical | chosen | reason | recurring? |
|
||||
|---|---|---|---|
|
||||
|
||||
## Top error classes
|
||||
|
||||
| error class | count | recovery pattern |
|
||||
|---|---|---|
|
||||
|
||||
## confusion_marker hot-spots
|
||||
|
||||
| context | count |
|
||||
|---|---|
|
||||
|
||||
## Candidates for owner review
|
||||
|
||||
### Candidate 1: `<title>`
|
||||
|
||||
- **Type**: new canonical chain L13+ / new ADR / boundary clarification / etc.
|
||||
- **Evidence**: refs to JSONL lines (file:line).
|
||||
- **Suggested action**: `<concrete edit>`.
|
||||
- **Cost / risk**: `<brief>`.
|
||||
|
||||
(repeat for each candidate; could be 0)
|
||||
|
||||
## Informational metrics (NOT alerts)
|
||||
|
||||
- Nodes used at least once this period: K / 60+
|
||||
- Nodes never used since beginning of observer logs: L / 60+ — **not a problem** per [feedback_brain_unused_tools_not_problem](../../../memory/feedback_brain_unused_tools_not_problem.md)
|
||||
@@ -0,0 +1,87 @@
|
||||
---
|
||||
name: ccpm
|
||||
description: "CCPM - spec-driven project management: PRD → Epic → GitHub Issues → parallel agents → shipped code. Use this skill for anything in the software delivery lifecycle: writing a PRD ('write a PRD for X', 'let's plan X', 'scope this out'), parsing a PRD into an epic, decomposing an epic into tasks, syncing to GitHub ('sync the X epic', 'push tasks to github'), starting work on an issue ('start working on issue N', 'let's work on issue N'), analyzing parallel work streams, running standups ('standup', 'run the standup'), checking status ('what's next', 'what's blocked', 'what are we working on'), closing issues, or merging an epic. Use ccpm any time the user is talking about shipping a feature, managing work, or tracking progress — even if they don't say 'ccpm' or 'PRD'. Do NOT use for: debugging code, writing tests, reviewing PRs, or raw GitHub issue/PR operations with no delivery context."
|
||||
---
|
||||
|
||||
# CCPM - Claude Code Project Manager
|
||||
|
||||
A spec-driven development workflow: PRD → Epic → GitHub Issues → Parallel Agents → Shipped Code.
|
||||
|
||||
## Core Philosophy
|
||||
|
||||
Requirements live in files, not heads. Every feature starts as a PRD, becomes a technical epic, decomposes into GitHub issues, and gets executed by parallel agents with full traceability.
|
||||
|
||||
## File Conventions
|
||||
|
||||
Before doing anything, read `references/conventions.md` for path standards, frontmatter schemas, and GitHub operation rules. These apply to all phases.
|
||||
|
||||
## The Five Phases
|
||||
|
||||
### 1. Plan — Capture requirements
|
||||
|
||||
**When**: User wants to define a new feature, product requirement, or scope of work.
|
||||
**Read**: `references/plan.md`
|
||||
**Covers**: Writing PRDs through guided brainstorming, converting PRDs to technical epics.
|
||||
|
||||
### 2. Structure — Break it down
|
||||
|
||||
**When**: An epic exists and needs to be decomposed into concrete tasks.
|
||||
**Read**: `references/structure.md`
|
||||
**Covers**: Epic decomposition into numbered task files with dependencies and parallelization.
|
||||
|
||||
### 3. Sync — Push to GitHub
|
||||
|
||||
**When**: Local epic/tasks need to become GitHub issues, progress needs to be posted as comments, or a bug is found and needs a linked issue created.
|
||||
**Read**: `references/sync.md`
|
||||
**Covers**: Epic sync (epic + tasks → GitHub issues), issue sync (progress comments), closing issues/epics, bug reporting against completed issues.
|
||||
|
||||
### 4. Execute — Start building
|
||||
|
||||
**When**: User wants to start working on one or more GitHub issues with parallel agents.
|
||||
**Read**: `references/execute.md`
|
||||
**Covers**: Issue analysis (parallel work stream identification), launching parallel agents, coordinating worktrees.
|
||||
|
||||
### 5. Track — Know where things stand
|
||||
|
||||
**When**: User asks for status, standup report, what's blocked, what's next, or needs to validate state.
|
||||
**Read**: `references/track.md`
|
||||
**Covers**: Status, standup, search, in-progress, next priority, blocked items, validation.
|
||||
|
||||
---
|
||||
|
||||
## Script-First Rule
|
||||
|
||||
For deterministic operations — anything that reads and reports without needing reasoning — always run the bash script directly rather than doing the work manually:
|
||||
|
||||
| What the user wants | Script to run |
|
||||
|---|---|
|
||||
| Project status | `bash references/scripts/status.sh` |
|
||||
| Standup report | `bash references/scripts/standup.sh` |
|
||||
| List all epics | `bash references/scripts/epic-list.sh` |
|
||||
| Show epic details | `bash references/scripts/epic-show.sh <name>` |
|
||||
| Epic status | `bash references/scripts/epic-status.sh <name>` |
|
||||
| List PRDs | `bash references/scripts/prd-list.sh` |
|
||||
| PRD status | `bash references/scripts/prd-status.sh` |
|
||||
| Search issues/tasks | `bash references/scripts/search.sh <query>` |
|
||||
| What's in progress | `bash references/scripts/in-progress.sh` |
|
||||
| What's next | `bash references/scripts/next.sh` |
|
||||
| What's blocked | `bash references/scripts/blocked.sh` |
|
||||
| Validate project state | `bash references/scripts/validate.sh` |
|
||||
|
||||
Use the LLM for work that requires reasoning: writing PRDs, analyzing parallelism, launching agents, synthesizing updates.
|
||||
|
||||
---
|
||||
|
||||
## Quick Reference
|
||||
|
||||
```
|
||||
Plan a feature: "I want to build X" or "create a PRD for X"
|
||||
Parse to epic: "turn the X PRD into an epic"
|
||||
Decompose: "break down the X epic into tasks"
|
||||
Sync to GitHub: "push the X epic to GitHub"
|
||||
Start an issue: "start working on issue 42"
|
||||
Check status: "what's our status" / "standup"
|
||||
What's next: "what should I work on next"
|
||||
Merge epic: "merge the X epic"
|
||||
Report a bug: "found a bug in issue 42" / "testing issue 42 revealed X"
|
||||
```
|
||||
@@ -0,0 +1,178 @@
|
||||
# Conventions — File Formats, Paths & Rules
|
||||
|
||||
Read this before doing any file operations across all phases.
|
||||
|
||||
---
|
||||
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
.claude/
|
||||
├── prds/
|
||||
│ └── <feature-name>.md # Product requirement documents
|
||||
├── epics/
|
||||
│ ├── <feature-name>/
|
||||
│ │ ├── epic.md # Technical epic
|
||||
│ │ ├── <N>.md # Task files (named by GitHub issue number after sync)
|
||||
│ │ ├── <N>-analysis.md # Parallel work stream analysis
|
||||
│ │ ├── github-mapping.md # Issue number → URL mapping
|
||||
│ │ ├── execution-status.md # Active agents tracker
|
||||
│ │ └── updates/
|
||||
│ │ └── <issue_N>/
|
||||
│ │ ├── stream-A.md # Per-agent progress
|
||||
│ │ ├── progress.md # Overall issue progress
|
||||
│ │ └── execution.md # Execution state
|
||||
│ └── archived/
|
||||
│ └── <feature-name>/ # Completed epics
|
||||
└── context/ # Project context docs (separate system)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Frontmatter Schemas
|
||||
|
||||
### PRD (.claude/prds/<name>.md)
|
||||
|
||||
```yaml
|
||||
---
|
||||
name: <feature-name> # kebab-case, matches filename
|
||||
description: <one-liner> # used in lists and summaries
|
||||
status: backlog | active | completed
|
||||
created: <ISO 8601> # date -u +"%Y-%m-%dT%H:%M:%SZ"
|
||||
---
|
||||
```
|
||||
|
||||
### Epic (.claude/epics/<name>/epic.md)
|
||||
|
||||
```yaml
|
||||
---
|
||||
name: <feature-name>
|
||||
status: backlog | in-progress | completed
|
||||
created: <ISO 8601>
|
||||
updated: <ISO 8601>
|
||||
progress: 0% # recalculated when tasks close
|
||||
prd: .claude/prds/<name>.md
|
||||
github: https://github.com/<owner>/<repo>/issues/<N> # set on sync
|
||||
---
|
||||
```
|
||||
|
||||
### Task (.claude/epics/<name>/<N>.md)
|
||||
|
||||
```yaml
|
||||
---
|
||||
name: <Task Title>
|
||||
status: open | in-progress | closed
|
||||
created: <ISO 8601>
|
||||
updated: <ISO 8601>
|
||||
github: https://github.com/<owner>/<repo>/issues/<N> # set on sync
|
||||
depends_on: [] # issue numbers this must wait for
|
||||
parallel: true # can run concurrently with non-conflicting tasks
|
||||
conflicts_with: [] # issue numbers that touch the same files
|
||||
---
|
||||
```
|
||||
|
||||
### Progress (.claude/epics/<name>/updates/<N>/progress.md)
|
||||
|
||||
```yaml
|
||||
---
|
||||
issue: <N>
|
||||
started: <ISO 8601>
|
||||
last_sync: <ISO 8601>
|
||||
completion: 0%
|
||||
---
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Datetime Rule
|
||||
|
||||
Always get real current datetime from the system — never use placeholder text:
|
||||
|
||||
```bash
|
||||
date -u +"%Y-%m-%dT%H:%M:%SZ"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Frontmatter Update Pattern
|
||||
|
||||
When updating a single frontmatter field in an existing file:
|
||||
|
||||
```bash
|
||||
sed -i.bak "/^<field>:/c\\<field>: <value>" <file>
|
||||
rm <file>.bak
|
||||
```
|
||||
|
||||
When stripping frontmatter to get body content for GitHub:
|
||||
|
||||
```bash
|
||||
sed '1,/^---$/d; 1,/^---$/d' <file> > /tmp/body.md
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## GitHub Operations
|
||||
|
||||
### Repository Safety Check (run before any write operation)
|
||||
|
||||
```bash
|
||||
remote_url=$(git remote get-url origin 2>/dev/null || echo "")
|
||||
if [[ "$remote_url" == *"automazeio/ccpm"* ]]; then
|
||||
echo "❌ Cannot write to the CCPM template repository."
|
||||
echo "Update remote: git remote set-url origin https://github.com/YOUR/REPO.git"
|
||||
exit 1
|
||||
fi
|
||||
REPO=$(echo "$remote_url" | sed 's|.*github.com[:/]||' | sed 's|\.git$||')
|
||||
```
|
||||
|
||||
### Authentication
|
||||
|
||||
Don't pre-check authentication. Run the `gh` command and handle failure:
|
||||
|
||||
```bash
|
||||
gh <command> || echo "❌ GitHub CLI failed. Run: gh auth login"
|
||||
```
|
||||
|
||||
### Getting Issue Numbers
|
||||
|
||||
```bash
|
||||
# From a task file's github field:
|
||||
grep 'github:' <file> | grep -oE '[0-9]+$'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Git / Worktree Conventions
|
||||
|
||||
- One branch per epic: `epic/<name>`
|
||||
- Worktrees live at `../epic-<name>/` (sibling to project root)
|
||||
- Always start branches from an up-to-date main:
|
||||
|
||||
```bash
|
||||
git checkout main && git pull origin main
|
||||
git worktree add ../epic-<name> -b epic/<name>
|
||||
```
|
||||
|
||||
- Commit format inside epics: `Issue #<N>: <description>`
|
||||
- Never use `--force` in any git operation
|
||||
|
||||
---
|
||||
|
||||
## Naming Conventions
|
||||
|
||||
- Feature names: kebab-case, lowercase, letters/numbers/hyphens, starts with a letter
|
||||
- Task files before sync: `001.md`, `002.md`, ... (sequential)
|
||||
- Task files after sync: renamed to GitHub issue number (e.g., `1234.md`)
|
||||
- Labels applied on sync: `epic`, `epic:<name>`, `feature` (for epics); `task`, `epic:<name>` (for tasks)
|
||||
|
||||
---
|
||||
|
||||
## Epic Progress Calculation
|
||||
|
||||
```bash
|
||||
total=$(ls .claude/epics/<name>/[0-9]*.md 2>/dev/null | wc -l)
|
||||
closed=$(grep -l '^status: closed' .claude/epics/<name>/[0-9]*.md 2>/dev/null | wc -l)
|
||||
progress=$((closed * 100 / total))
|
||||
```
|
||||
|
||||
Update epic frontmatter when any task closes.
|
||||
@@ -0,0 +1,223 @@
|
||||
# Execute — Start Building with Parallel Agents
|
||||
|
||||
This phase covers analyzing GitHub issues for parallel work streams and launching agents to execute them.
|
||||
|
||||
---
|
||||
|
||||
## Issue Analysis
|
||||
|
||||
**Trigger**: User wants to understand how to parallelize work on an issue before starting.
|
||||
|
||||
### Preflight
|
||||
|
||||
- Find the local task file: check `.claude/epics/*/<N>.md` first, then search for `github:.*issues/<N>` in frontmatter.
|
||||
- If not found: "❌ No local task for issue #<N>. Run a sync first."
|
||||
|
||||
### Process
|
||||
|
||||
Get issue details: `gh issue view <N> --json title,body,labels`
|
||||
|
||||
Read the local task file fully. Identify independent work streams by asking:
|
||||
|
||||
- Which files will be created/modified?
|
||||
- Which changes can happen simultaneously without conflict?
|
||||
- What are the dependencies between changes?
|
||||
|
||||
**Common stream patterns:**
|
||||
|
||||
- Database Layer: schema, migrations, models
|
||||
- Service Layer: business logic, data access
|
||||
- API Layer: endpoints, validation, middleware
|
||||
- UI Layer: components, pages, styles
|
||||
- Test Layer: unit tests, integration tests
|
||||
|
||||
Create `.claude/epics/<epic_name>/<N>-analysis.md`:
|
||||
|
||||
```markdown
|
||||
---
|
||||
issue: <N>
|
||||
title: <title>
|
||||
analyzed: <run: date -u +"%Y-%m-%dT%H:%M:%SZ">
|
||||
estimated_hours: <total>
|
||||
parallelization_factor: <1.0-5.0>
|
||||
---
|
||||
|
||||
# Parallel Work Analysis: Issue #<N>
|
||||
|
||||
## Overview
|
||||
|
||||
## Parallel Streams
|
||||
|
||||
### Stream A: <Name>
|
||||
**Scope**:
|
||||
**Files**:
|
||||
**Can Start**: immediately
|
||||
**Estimated Hours**:
|
||||
**Dependencies**: none
|
||||
|
||||
### Stream B: <Name>
|
||||
**Scope**:
|
||||
**Files**:
|
||||
**Can Start**: after Stream A
|
||||
**Dependencies**: Stream A
|
||||
|
||||
## Coordination Points
|
||||
### Shared Files
|
||||
### Sequential Requirements
|
||||
|
||||
## Conflict Risk Assessment
|
||||
|
||||
## Parallelization Strategy
|
||||
|
||||
## Expected Timeline
|
||||
- With parallel execution: <max_stream_hours>h wall time
|
||||
- Without: <sum_all_hours>h
|
||||
- Efficiency gain: <pct>%
|
||||
```
|
||||
|
||||
**Output**: "✅ Analysis complete for issue #<N> — N parallel streams identified. Ready to start? Say: start issue <N>"
|
||||
|
||||
---
|
||||
|
||||
## Starting an Issue
|
||||
|
||||
**Trigger**: User wants to begin work on a specific GitHub issue.
|
||||
|
||||
### Preflight
|
||||
|
||||
1. Verify issue exists and is open: `gh issue view <N> --json state,title,labels,body`
|
||||
2. Find local task file (as above).
|
||||
3. Check for analysis file: `.claude/epics/*/<N>-analysis.md` — if missing, run analysis first (or do both in sequence: analyze then start).
|
||||
4. Verify epic worktree exists: `git worktree list | grep "epic-<name>"` — if not: "❌ No worktree. Sync the epic first."
|
||||
|
||||
### Process
|
||||
|
||||
**Step 1 — Read the analysis**, identify which streams can start immediately vs. which have dependencies.
|
||||
|
||||
**Step 2 — Create progress tracking:**
|
||||
|
||||
```bash
|
||||
mkdir -p .claude/epics/<epic>/updates/<N>
|
||||
current_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
|
||||
```
|
||||
|
||||
Create `.claude/epics/<epic>/updates/<N>/stream-<X>.md` for each stream:
|
||||
|
||||
```markdown
|
||||
---
|
||||
issue: <N>
|
||||
stream: <stream_name>
|
||||
started: <datetime>
|
||||
status: in_progress
|
||||
---
|
||||
## Scope
|
||||
## Progress
|
||||
- Starting implementation
|
||||
```
|
||||
|
||||
**Step 3 — Launch parallel agents** for each stream that can start immediately:
|
||||
|
||||
```yaml
|
||||
Task:
|
||||
description: "Issue #<N> Stream <X>"
|
||||
subagent_type: "general-purpose"
|
||||
prompt: |
|
||||
You are working on Issue #<N> in the epic worktree at: ../epic-<name>/
|
||||
|
||||
Your stream: <stream_name>
|
||||
Your scope — files to modify: <file_patterns>
|
||||
Work to complete: <stream_description>
|
||||
|
||||
Instructions:
|
||||
1. Read full task from: .claude/epics/<epic>/<N>.md
|
||||
2. Read analysis from: .claude/epics/<epic>/<N>-analysis.md
|
||||
3. Work ONLY in your assigned files
|
||||
4. Commit frequently: "Issue #<N>: <specific change>"
|
||||
5. Update progress in: .claude/epics/<epic>/updates/<N>/stream-<X>.md
|
||||
6. If you need to touch files outside your scope, note it in your progress file and wait
|
||||
7. Never use --force on git operations
|
||||
|
||||
Complete your stream's work and mark status: completed when done.
|
||||
```
|
||||
|
||||
Streams with unmet dependencies are queued — launch them as their dependencies complete.
|
||||
|
||||
**Step 4 — Assign on GitHub:**
|
||||
|
||||
```bash
|
||||
gh issue edit <N> --add-assignee @me --add-label "in-progress"
|
||||
```
|
||||
|
||||
**Step 5 — Create execution status file** at `.claude/epics/<epic>/updates/<N>/execution.md`:
|
||||
|
||||
```markdown
|
||||
## Active Streams
|
||||
- Stream A: <name> — Started <time>
|
||||
- Stream B: <name> — Started <time>
|
||||
|
||||
## Queued
|
||||
- Stream C: <name> — Waiting on Stream A
|
||||
|
||||
## Completed
|
||||
(none yet)
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
✅ Started work on issue #<N>
|
||||
|
||||
Launched N agents:
|
||||
Stream A: <name> ✓ Started
|
||||
Stream B: <name> ✓ Started
|
||||
Stream C: <name> ⏸ Waiting (depends on A)
|
||||
|
||||
Monitor: check progress in .claude/epics/<epic>/updates/<N>/
|
||||
Sync updates: "sync issue <N>"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Starting a Full Epic
|
||||
|
||||
**Trigger**: User wants to launch parallel agents across all ready issues in an epic at once.
|
||||
|
||||
### Preflight
|
||||
|
||||
- Verify `.claude/epics/<name>/epic.md` exists and has a `github:` field (i.e., it's been synced).
|
||||
- Check for uncommitted changes: `git status --porcelain` — block if dirty.
|
||||
- Verify epic branch exists: `git branch -a | grep "epic/<name>"`
|
||||
|
||||
### Process
|
||||
|
||||
**Step 1 — Read all task files** in `.claude/epics/<name>/`. Parse frontmatter for `status`, `depends_on`, `parallel`.
|
||||
|
||||
**Step 2 — Categorize tasks:**
|
||||
|
||||
- Ready: status=open, no unmet depends_on
|
||||
- Blocked: has unmet depends_on
|
||||
- In Progress: already has an execution file
|
||||
- Complete: status=closed
|
||||
|
||||
**Step 3 — Analyze any ready tasks** that don't have an analysis file yet (run issue analysis inline).
|
||||
|
||||
**Step 4 — Launch agents** for all ready tasks following the same per-issue agent launch pattern above.
|
||||
|
||||
**Step 5 — Create/update** `.claude/epics/<name>/execution-status.md` with all active agents and queued issues.
|
||||
|
||||
**Step 6 — As agents complete**, check if blocked issues are now unblocked and launch those agents.
|
||||
|
||||
---
|
||||
|
||||
## Agent Coordination Rules
|
||||
|
||||
When multiple agents work in the same worktree simultaneously:
|
||||
|
||||
- Each agent works only on files in its assigned stream scope.
|
||||
- Agents commit frequently with `Issue #<N>: <description>` format.
|
||||
- Before modifying a shared file, check `git status <file>` — if another agent has it modified, wait and pull first.
|
||||
- Agents sync via commits: `git pull --rebase origin epic/<name>` before starting new file work.
|
||||
- Conflicts are never auto-resolved — agents report them and pause.
|
||||
- No `--force` flags ever.
|
||||
|
||||
Shared files that commonly need coordination (types, config, package.json) should be handled by one designated stream; others pull after that commit.
|
||||
@@ -0,0 +1,111 @@
|
||||
# Plan — Capture Requirements
|
||||
|
||||
This phase turns an idea into a structured PRD, then converts the PRD into a technical epic ready for decomposition.
|
||||
|
||||
---
|
||||
|
||||
## Writing a PRD
|
||||
|
||||
**Trigger**: User wants to plan a new feature, product requirement, or area of work.
|
||||
|
||||
### Preflight
|
||||
|
||||
- Check if `.claude/prds/<name>.md` already exists — if so, confirm overwrite before proceeding.
|
||||
- Ensure `.claude/prds/` directory exists; create it if not.
|
||||
- Feature name must be kebab-case (lowercase, letters/numbers/hyphens, starts with a letter). If not: "❌ Feature name must be kebab-case. Example: user-auth, payment-v2"
|
||||
|
||||
### Process
|
||||
|
||||
Conduct a genuine brainstorming session before writing anything. Ask the user:
|
||||
|
||||
- What problem does this solve?
|
||||
- Who are the users affected?
|
||||
- What does success look like?
|
||||
- What's explicitly out of scope?
|
||||
- What are the constraints (tech, time, resources)?
|
||||
|
||||
Then write `.claude/prds/<name>.md` with this frontmatter and structure:
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: <feature-name>
|
||||
description: <one-line summary>
|
||||
status: backlog
|
||||
created: <run: date -u +"%Y-%m-%dT%H:%M:%SZ">
|
||||
---
|
||||
|
||||
# PRD: <feature-name>
|
||||
|
||||
## Executive Summary
|
||||
## Problem Statement
|
||||
## User Stories
|
||||
## Functional Requirements
|
||||
## Non-Functional Requirements
|
||||
## Success Criteria
|
||||
## Constraints & Assumptions
|
||||
## Out of Scope
|
||||
## Dependencies
|
||||
```
|
||||
|
||||
**Quality gates before saving:**
|
||||
|
||||
- No placeholder text in any section
|
||||
- User stories include acceptance criteria
|
||||
- Success criteria are measurable
|
||||
- Out of scope is explicitly listed
|
||||
|
||||
**After creation**: Confirm "✅ PRD created: `.claude/prds/<name>.md`" and suggest: "Ready to create technical epic? Say: parse the <name> PRD"
|
||||
|
||||
---
|
||||
|
||||
## Parsing a PRD into a Technical Epic
|
||||
|
||||
**Trigger**: User wants to convert an existing PRD into a technical implementation plan.
|
||||
|
||||
### Preflight
|
||||
|
||||
- Verify `.claude/prds/<name>.md` exists with valid frontmatter (name, description, status, created).
|
||||
- Check if `.claude/epics/<name>/epic.md` already exists — confirm overwrite if so.
|
||||
|
||||
### Process
|
||||
|
||||
Read the PRD fully, then produce `.claude/epics/<name>/epic.md`:
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: <feature-name>
|
||||
status: backlog
|
||||
created: <run: date -u +"%Y-%m-%dT%H:%M:%SZ">
|
||||
progress: 0%
|
||||
prd: .claude/prds/<name>.md
|
||||
github: (will be set on sync)
|
||||
---
|
||||
|
||||
# Epic: <feature-name>
|
||||
|
||||
## Overview
|
||||
## Architecture Decisions
|
||||
## Technical Approach
|
||||
### Frontend Components
|
||||
### Backend Services
|
||||
### Infrastructure
|
||||
## Implementation Strategy
|
||||
## Task Breakdown Preview
|
||||
## Dependencies
|
||||
## Success Criteria (Technical)
|
||||
## Estimated Effort
|
||||
```
|
||||
|
||||
**Key constraints:**
|
||||
|
||||
- Aim for ≤10 tasks total — prefer simplicity over completeness.
|
||||
- Look for ways to leverage existing functionality before creating new code.
|
||||
- Identify parallelization opportunities in the task breakdown preview.
|
||||
|
||||
**After creation**: Confirm "✅ Epic created: `.claude/epics/<name>/epic.md`" and suggest: "Ready to decompose into tasks? Say: decompose the <name> epic"
|
||||
|
||||
---
|
||||
|
||||
## Editing a PRD or Epic
|
||||
|
||||
Read the file first, make targeted edits preserving all frontmatter. Update the `updated` frontmatter field with current datetime.
|
||||
@@ -0,0 +1,67 @@
|
||||
#!/bin/bash
|
||||
echo "Getting tasks..."
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
echo "🚫 Blocked Tasks"
|
||||
echo "================"
|
||||
echo ""
|
||||
|
||||
found=0
|
||||
|
||||
for epic_dir in .claude/epics/*/; do
|
||||
[ -d "$epic_dir" ] || continue
|
||||
epic_name=$(basename "$epic_dir")
|
||||
|
||||
for task_file in "$epic_dir"/[0-9]*.md; do
|
||||
[ -f "$task_file" ] || continue
|
||||
|
||||
# Check if task is open
|
||||
status=$(grep "^status:" "$task_file" | head -1 | sed 's/^status: *//')
|
||||
if [ "$status" != "open" ] && [ -n "$status" ]; then
|
||||
continue
|
||||
fi
|
||||
|
||||
# Check for dependencies
|
||||
deps_line=$(grep "^depends_on:" "$task_file" | head -1)
|
||||
if [ -n "$deps_line" ]; then
|
||||
deps=$(echo "$deps_line" | sed 's/^depends_on: *//' | sed 's/^\[//' | sed 's/\]$//' | sed 's/,/ /g' | sed 's/^[[:space:]]*//' | sed 's/[[:space:]]*$//')
|
||||
[ -z "$deps" ] && deps=""
|
||||
else
|
||||
deps=""
|
||||
fi
|
||||
|
||||
if [ -n "$deps" ] && [ "$deps" != "depends_on:" ]; then
|
||||
task_name=$(grep "^name:" "$task_file" | head -1 | sed 's/^name: *//')
|
||||
task_num=$(basename "$task_file" .md)
|
||||
|
||||
echo "⏸️ Task #$task_num - $task_name"
|
||||
echo " Epic: $epic_name"
|
||||
echo " Blocked by: [$deps]"
|
||||
|
||||
# Check status of dependencies
|
||||
open_deps=""
|
||||
for dep in $deps; do
|
||||
dep_file="$epic_dir$dep.md"
|
||||
if [ -f "$dep_file" ]; then
|
||||
dep_status=$(grep "^status:" "$dep_file" | head -1 | sed 's/^status: *//')
|
||||
[ "$dep_status" = "open" ] && open_deps="$open_deps #$dep"
|
||||
fi
|
||||
done
|
||||
|
||||
[ -n "$open_deps" ] && echo " Waiting for:$open_deps"
|
||||
echo ""
|
||||
((found++))
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
if [ $found -eq 0 ]; then
|
||||
echo "No blocked tasks found!"
|
||||
echo ""
|
||||
echo "💡 All tasks with dependencies are either completed or in progress."
|
||||
else
|
||||
echo "📊 Total blocked: $found tasks"
|
||||
fi
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/bin/bash
|
||||
echo "Getting epics..."
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
[ ! -d ".claude/epics" ] && echo "📁 No epics directory found. Create your first epic with: /pm:prd-parse <feature-name>" && exit 0
|
||||
[ -z "$(ls -d .claude/epics/*/ 2>/dev/null)" ] && echo "📁 No epics found. Create your first epic with: /pm:prd-parse <feature-name>" && exit 0
|
||||
|
||||
echo "📚 Project Epics"
|
||||
echo "================"
|
||||
echo ""
|
||||
|
||||
# Initialize arrays to store epics by status
|
||||
planning_epics=""
|
||||
in_progress_epics=""
|
||||
completed_epics=""
|
||||
|
||||
# Process all epics
|
||||
for dir in .claude/epics/*/; do
|
||||
[ -d "$dir" ] || continue
|
||||
[ -f "$dir/epic.md" ] || continue
|
||||
|
||||
# Extract metadata
|
||||
n=$(grep "^name:" "$dir/epic.md" | head -1 | sed 's/^name: *//')
|
||||
s=$(grep "^status:" "$dir/epic.md" | head -1 | sed 's/^status: *//' | tr '[:upper:]' '[:lower:]')
|
||||
p=$(grep "^progress:" "$dir/epic.md" | head -1 | sed 's/^progress: *//')
|
||||
g=$(grep "^github:" "$dir/epic.md" | head -1 | sed 's/^github: *//')
|
||||
|
||||
# Defaults
|
||||
[ -z "$n" ] && n=$(basename "$dir")
|
||||
[ -z "$p" ] && p="0%"
|
||||
|
||||
# Count tasks
|
||||
t=$(ls "$dir"/[0-9]*.md 2>/dev/null | wc -l)
|
||||
|
||||
# Format output with GitHub issue number if available
|
||||
if [ -n "$g" ]; then
|
||||
i=$(echo "$g" | grep -o '/[0-9]*$' | tr -d '/')
|
||||
entry=" 📋 ${dir}epic.md (#$i) - $p complete ($t tasks)"
|
||||
else
|
||||
entry=" 📋 ${dir}epic.md - $p complete ($t tasks)"
|
||||
fi
|
||||
|
||||
# Categorize by status (handle various status values)
|
||||
case "$s" in
|
||||
planning|draft|"")
|
||||
planning_epics="${planning_epics}${entry}\n"
|
||||
;;
|
||||
in-progress|in_progress|active|started)
|
||||
in_progress_epics="${in_progress_epics}${entry}\n"
|
||||
;;
|
||||
completed|complete|done|closed|finished)
|
||||
completed_epics="${completed_epics}${entry}\n"
|
||||
;;
|
||||
*)
|
||||
# Default to planning for unknown statuses
|
||||
planning_epics="${planning_epics}${entry}\n"
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
# Display categorized epics
|
||||
echo "📝 Planning:"
|
||||
if [ -n "$planning_epics" ]; then
|
||||
echo -e "$planning_epics" | sed '/^$/d'
|
||||
else
|
||||
echo " (none)"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "🚀 In Progress:"
|
||||
if [ -n "$in_progress_epics" ]; then
|
||||
echo -e "$in_progress_epics" | sed '/^$/d'
|
||||
else
|
||||
echo " (none)"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "✅ Completed:"
|
||||
if [ -n "$completed_epics" ]; then
|
||||
echo -e "$completed_epics" | sed '/^$/d'
|
||||
else
|
||||
echo " (none)"
|
||||
fi
|
||||
|
||||
# Summary
|
||||
echo ""
|
||||
echo "📊 Summary"
|
||||
total=$(ls -d .claude/epics/*/ 2>/dev/null | wc -l)
|
||||
tasks=$(find .claude/epics -name "[0-9]*.md" 2>/dev/null | wc -l)
|
||||
echo " Total epics: $total"
|
||||
echo " Total tasks: $tasks"
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/bin/bash
|
||||
|
||||
epic_name="$1"
|
||||
|
||||
if [ -z "$epic_name" ]; then
|
||||
echo "❌ Please provide an epic name"
|
||||
echo "Usage: /pm:epic-show <epic-name>"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Getting epic..."
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
epic_dir=".claude/epics/$epic_name"
|
||||
epic_file="$epic_dir/epic.md"
|
||||
|
||||
if [ ! -f "$epic_file" ]; then
|
||||
echo "❌ Epic not found: $epic_name"
|
||||
echo ""
|
||||
echo "Available epics:"
|
||||
for dir in .claude/epics/*/; do
|
||||
[ -d "$dir" ] && echo " • $(basename "$dir")"
|
||||
done
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Display epic details
|
||||
echo "📚 Epic: $epic_name"
|
||||
echo "================================"
|
||||
echo ""
|
||||
|
||||
# Extract metadata
|
||||
status=$(grep "^status:" "$epic_file" | head -1 | sed 's/^status: *//')
|
||||
progress=$(grep "^progress:" "$epic_file" | head -1 | sed 's/^progress: *//')
|
||||
github=$(grep "^github:" "$epic_file" | head -1 | sed 's/^github: *//')
|
||||
created=$(grep "^created:" "$epic_file" | head -1 | sed 's/^created: *//')
|
||||
|
||||
echo "📊 Metadata:"
|
||||
echo " Status: ${status:-planning}"
|
||||
echo " Progress: ${progress:-0%}"
|
||||
[ -n "$github" ] && echo " GitHub: $github"
|
||||
echo " Created: ${created:-unknown}"
|
||||
echo ""
|
||||
|
||||
# Show tasks
|
||||
echo "📝 Tasks:"
|
||||
task_count=0
|
||||
open_count=0
|
||||
closed_count=0
|
||||
|
||||
for task_file in "$epic_dir"/[0-9]*.md; do
|
||||
[ -f "$task_file" ] || continue
|
||||
|
||||
task_num=$(basename "$task_file" .md)
|
||||
task_name=$(grep "^name:" "$task_file" | head -1 | sed 's/^name: *//')
|
||||
task_status=$(grep "^status:" "$task_file" | head -1 | sed 's/^status: *//')
|
||||
parallel=$(grep "^parallel:" "$task_file" | head -1 | sed 's/^parallel: *//')
|
||||
|
||||
if [ "$task_status" = "closed" ] || [ "$task_status" = "completed" ]; then
|
||||
echo " ✅ #$task_num - $task_name"
|
||||
((closed_count++))
|
||||
else
|
||||
echo " ⬜ #$task_num - $task_name"
|
||||
[ "$parallel" = "true" ] && echo -n " (parallel)"
|
||||
((open_count++))
|
||||
fi
|
||||
|
||||
((task_count++))
|
||||
done
|
||||
|
||||
if [ $task_count -eq 0 ]; then
|
||||
echo " No tasks created yet"
|
||||
echo " Run: /pm:epic-decompose $epic_name"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "📈 Statistics:"
|
||||
echo " Total tasks: $task_count"
|
||||
echo " Open: $open_count"
|
||||
echo " Closed: $closed_count"
|
||||
[ $task_count -gt 0 ] && echo " Completion: $((closed_count * 100 / task_count))%"
|
||||
|
||||
# Next actions
|
||||
echo ""
|
||||
echo "💡 Actions:"
|
||||
[ $task_count -eq 0 ] && echo " • Decompose into tasks: /pm:epic-decompose $epic_name"
|
||||
[ -z "$github" ] && [ $task_count -gt 0 ] && echo " • Sync to GitHub: /pm:epic-sync $epic_name"
|
||||
[ -n "$github" ] && [ "$status" != "completed" ] && echo " • Start work: /pm:epic-start $epic_name"
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "Getting status..."
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
epic_name="$1"
|
||||
|
||||
if [ -z "$epic_name" ]; then
|
||||
echo "❌ Please specify an epic name"
|
||||
echo "Usage: /pm:epic-status <epic-name>"
|
||||
echo ""
|
||||
echo "Available epics:"
|
||||
for dir in .claude/epics/*/; do
|
||||
[ -d "$dir" ] && echo " • $(basename "$dir")"
|
||||
done
|
||||
exit 1
|
||||
else
|
||||
# Show status for specific epic
|
||||
epic_dir=".claude/epics/$epic_name"
|
||||
epic_file="$epic_dir/epic.md"
|
||||
|
||||
if [ ! -f "$epic_file" ]; then
|
||||
echo "❌ Epic not found: $epic_name"
|
||||
echo ""
|
||||
echo "Available epics:"
|
||||
for dir in .claude/epics/*/; do
|
||||
[ -d "$dir" ] && echo " • $(basename "$dir")"
|
||||
done
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "📚 Epic Status: $epic_name"
|
||||
echo "================================"
|
||||
echo ""
|
||||
|
||||
# Extract metadata
|
||||
status=$(grep "^status:" "$epic_file" | head -1 | sed 's/^status: *//')
|
||||
progress=$(grep "^progress:" "$epic_file" | head -1 | sed 's/^progress: *//')
|
||||
github=$(grep "^github:" "$epic_file" | head -1 | sed 's/^github: *//')
|
||||
|
||||
# Count tasks
|
||||
total=0
|
||||
open=0
|
||||
closed=0
|
||||
blocked=0
|
||||
|
||||
# Use find to safely iterate over task files
|
||||
for task_file in "$epic_dir"/[0-9]*.md; do
|
||||
[ -f "$task_file" ] || continue
|
||||
((total++))
|
||||
|
||||
task_status=$(grep "^status:" "$task_file" | head -1 | sed 's/^status: *//')
|
||||
deps=$(grep "^depends_on:" "$task_file" | head -1 | sed 's/^depends_on: *\[//' | sed 's/\]//')
|
||||
|
||||
if [ "$task_status" = "closed" ] || [ "$task_status" = "completed" ]; then
|
||||
((closed++))
|
||||
elif [ -n "$deps" ] && [ "$deps" != "depends_on:" ]; then
|
||||
((blocked++))
|
||||
else
|
||||
((open++))
|
||||
fi
|
||||
done
|
||||
|
||||
# Display progress bar
|
||||
if [ $total -gt 0 ]; then
|
||||
percent=$((closed * 100 / total))
|
||||
filled=$((percent * 20 / 100))
|
||||
empty=$((20 - filled))
|
||||
|
||||
echo -n "Progress: ["
|
||||
[ $filled -gt 0 ] && printf '%0.s█' $(seq 1 $filled)
|
||||
[ $empty -gt 0 ] && printf '%0.s░' $(seq 1 $empty)
|
||||
echo "] $percent%"
|
||||
else
|
||||
echo "Progress: No tasks created"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "📊 Breakdown:"
|
||||
echo " Total tasks: $total"
|
||||
echo " ✅ Completed: $closed"
|
||||
echo " 🔄 Available: $open"
|
||||
echo " ⏸️ Blocked: $blocked"
|
||||
|
||||
[ -n "$github" ] && echo ""
|
||||
[ -n "$github" ] && echo "🔗 GitHub: $github"
|
||||
fi
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/bin/bash
|
||||
echo "Helping..."
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
echo "📚 Claude Code PM - Project Management System"
|
||||
echo "============================================="
|
||||
echo ""
|
||||
echo "🎯 Quick Start Workflow"
|
||||
echo " 1. /pm:prd-new <name> - Create a new PRD"
|
||||
echo " 2. /pm:prd-parse <name> - Convert PRD to epic"
|
||||
echo " 3. /pm:epic-decompose <name> - Break into tasks"
|
||||
echo " 4. /pm:epic-sync <name> - Push to GitHub"
|
||||
echo " 5. /pm:epic-start <name> - Start parallel execution"
|
||||
echo ""
|
||||
echo "📄 PRD Commands"
|
||||
echo " /pm:prd-new <name> - Launch brainstorming for new product requirement"
|
||||
echo " /pm:prd-parse <name> - Convert PRD to implementation epic"
|
||||
echo " /pm:prd-list - List all PRDs"
|
||||
echo " /pm:prd-edit <name> - Edit existing PRD"
|
||||
echo " /pm:prd-status - Show PRD implementation status"
|
||||
echo ""
|
||||
echo "📚 Epic Commands"
|
||||
echo " /pm:epic-decompose <name> - Break epic into task files"
|
||||
echo " /pm:epic-sync <name> - Push epic and tasks to GitHub"
|
||||
echo " /pm:epic-oneshot <name> - Decompose and sync in one command"
|
||||
echo " /pm:epic-list - List all epics"
|
||||
echo " /pm:epic-show <name> - Display epic and its tasks"
|
||||
echo " /pm:epic-status [name] - Show epic progress"
|
||||
echo " /pm:epic-close <name> - Mark epic as complete"
|
||||
echo " /pm:epic-edit <name> - Edit epic details"
|
||||
echo " /pm:epic-refresh <name> - Update epic progress from tasks"
|
||||
echo " /pm:epic-start <name> - Launch parallel agent execution"
|
||||
echo ""
|
||||
echo "📝 Issue Commands"
|
||||
echo " /pm:issue-show <num> - Display issue and sub-issues"
|
||||
echo " /pm:issue-status <num> - Check issue status"
|
||||
echo " /pm:issue-start <num> - Begin work with specialized agent"
|
||||
echo " /pm:issue-sync <num> - Push updates to GitHub"
|
||||
echo " /pm:issue-close <num> - Mark issue as complete"
|
||||
echo " /pm:issue-reopen <num> - Reopen closed issue"
|
||||
echo " /pm:issue-edit <num> - Edit issue details"
|
||||
echo " /pm:issue-analyze <num> - Analyze for parallel work streams"
|
||||
echo ""
|
||||
echo "🔄 Workflow Commands"
|
||||
echo " /pm:next - Show next priority tasks"
|
||||
echo " /pm:status - Overall project dashboard"
|
||||
echo " /pm:standup - Daily standup report"
|
||||
echo " /pm:blocked - Show blocked tasks"
|
||||
echo " /pm:in-progress - List work in progress"
|
||||
echo ""
|
||||
echo "🔗 Sync Commands"
|
||||
echo " /pm:sync - Full bidirectional sync with GitHub"
|
||||
echo " /pm:import <issue> - Import existing GitHub issues"
|
||||
echo ""
|
||||
echo "🔧 Maintenance Commands"
|
||||
echo " /pm:validate - Check system integrity"
|
||||
echo " /pm:clean - Archive completed work"
|
||||
echo " /pm:search <query> - Search across all content"
|
||||
echo ""
|
||||
echo "⚙️ Setup Commands"
|
||||
echo " /pm:init - Install dependencies and configure GitHub"
|
||||
echo " /pm:help - Show this help message"
|
||||
echo ""
|
||||
echo "💡 Tips"
|
||||
echo " • Use /pm:next to find available work"
|
||||
echo " • Run /pm:status for quick overview"
|
||||
echo " • Epic workflow: prd-new → prd-parse → epic-decompose → epic-sync"
|
||||
echo " • View README.md for complete documentation"
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,74 @@
|
||||
#!/bin/bash
|
||||
echo "Getting status..."
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
echo "🔄 In Progress Work"
|
||||
echo "==================="
|
||||
echo ""
|
||||
|
||||
# Check for active work in updates directories
|
||||
found=0
|
||||
|
||||
if [ -d ".claude/epics" ]; then
|
||||
for updates_dir in .claude/epics/*/updates/*/; do
|
||||
[ -d "$updates_dir" ] || continue
|
||||
|
||||
issue_num=$(basename "$updates_dir")
|
||||
epic_name=$(basename $(dirname $(dirname "$updates_dir")))
|
||||
|
||||
if [ -f "$updates_dir/progress.md" ]; then
|
||||
completion=$(grep "^completion:" "$updates_dir/progress.md" | head -1 | sed 's/^completion: *//')
|
||||
[ -z "$completion" ] && completion="0%"
|
||||
|
||||
# Get task name from the task file
|
||||
task_file=".claude/epics/$epic_name/$issue_num.md"
|
||||
if [ -f "$task_file" ]; then
|
||||
task_name=$(grep "^name:" "$task_file" | head -1 | sed 's/^name: *//')
|
||||
else
|
||||
task_name="Unknown task"
|
||||
fi
|
||||
|
||||
echo "📝 Issue #$issue_num - $task_name"
|
||||
echo " Epic: $epic_name"
|
||||
echo " Progress: $completion complete"
|
||||
|
||||
# Check for recent updates
|
||||
if [ -f "$updates_dir/progress.md" ]; then
|
||||
last_update=$(grep "^last_sync:" "$updates_dir/progress.md" | head -1 | sed 's/^last_sync: *//')
|
||||
[ -n "$last_update" ] && echo " Last update: $last_update"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
((found++))
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
# Also check for in-progress epics
|
||||
echo "📚 Active Epics:"
|
||||
for epic_dir in .claude/epics/*/; do
|
||||
[ -d "$epic_dir" ] || continue
|
||||
[ -f "$epic_dir/epic.md" ] || continue
|
||||
|
||||
status=$(grep "^status:" "$epic_dir/epic.md" | head -1 | sed 's/^status: *//')
|
||||
if [ "$status" = "in-progress" ] || [ "$status" = "active" ]; then
|
||||
epic_name=$(grep "^name:" "$epic_dir/epic.md" | head -1 | sed 's/^name: *//')
|
||||
progress=$(grep "^progress:" "$epic_dir/epic.md" | head -1 | sed 's/^progress: *//')
|
||||
[ -z "$epic_name" ] && epic_name=$(basename "$epic_dir")
|
||||
[ -z "$progress" ] && progress="0%"
|
||||
|
||||
echo " • $epic_name - $progress complete"
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
if [ $found -eq 0 ]; then
|
||||
echo "No active work items found."
|
||||
echo ""
|
||||
echo "💡 Start work with: /pm:next"
|
||||
else
|
||||
echo "📊 Total active items: $found"
|
||||
fi
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,192 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "Initializing..."
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
echo " ██████╗ ██████╗██████╗ ███╗ ███╗"
|
||||
echo "██╔════╝██╔════╝██╔══██╗████╗ ████║"
|
||||
echo "██║ ██║ ██████╔╝██╔████╔██║"
|
||||
echo "╚██████╗╚██████╗██║ ██║ ╚═╝ ██║"
|
||||
echo " ╚═════╝ ╚═════╝╚═╝ ╚═╝ ╚═╝"
|
||||
|
||||
echo "┌─────────────────────────────────┐"
|
||||
echo "│ Claude Code Project Management │"
|
||||
echo "│ by https://x.com/aroussi │"
|
||||
echo "└─────────────────────────────────┘"
|
||||
echo "https://github.com/automazeio/ccpm"
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
echo "🚀 Initializing Claude Code PM System"
|
||||
echo "======================================"
|
||||
echo ""
|
||||
|
||||
# Check for required tools
|
||||
echo "🔍 Checking dependencies..."
|
||||
|
||||
# Check gh CLI
|
||||
if command -v gh &> /dev/null; then
|
||||
echo " ✅ GitHub CLI (gh) installed"
|
||||
else
|
||||
echo " ❌ GitHub CLI (gh) not found"
|
||||
echo ""
|
||||
echo " Installing gh..."
|
||||
if command -v brew &> /dev/null; then
|
||||
brew install gh
|
||||
elif command -v apt-get &> /dev/null; then
|
||||
sudo apt-get update && sudo apt-get install gh
|
||||
else
|
||||
echo " Please install GitHub CLI manually: https://cli.github.com/"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Check gh auth status
|
||||
echo ""
|
||||
echo "🔐 Checking GitHub authentication..."
|
||||
if gh auth status &> /dev/null; then
|
||||
echo " ✅ GitHub authenticated"
|
||||
else
|
||||
echo " ⚠️ GitHub not authenticated"
|
||||
echo " Running: gh auth login"
|
||||
gh auth login
|
||||
fi
|
||||
|
||||
# Check for gh-sub-issue extension
|
||||
echo ""
|
||||
echo "📦 Checking gh extensions..."
|
||||
if gh extension list | grep -q "yahsan2/gh-sub-issue"; then
|
||||
echo " ✅ gh-sub-issue extension installed"
|
||||
else
|
||||
echo " 📥 Installing gh-sub-issue extension..."
|
||||
gh extension install yahsan2/gh-sub-issue
|
||||
fi
|
||||
|
||||
# Create directory structure
|
||||
echo ""
|
||||
echo "📁 Creating directory structure..."
|
||||
mkdir -p .claude/prds
|
||||
mkdir -p .claude/epics
|
||||
mkdir -p .claude/rules
|
||||
mkdir -p .claude/agents
|
||||
mkdir -p .claude/scripts/pm
|
||||
echo " ✅ Directories created"
|
||||
|
||||
# Copy scripts if in main repo
|
||||
if [ -d "scripts/pm" ] && [ ! "$(pwd)" = *"/.claude"* ]; then
|
||||
echo ""
|
||||
echo "📝 Copying PM scripts..."
|
||||
cp -r scripts/pm/* .claude/scripts/pm/
|
||||
chmod +x .claude/scripts/pm/*.sh
|
||||
echo " ✅ Scripts copied and made executable"
|
||||
fi
|
||||
|
||||
# Check for git
|
||||
echo ""
|
||||
echo "🔗 Checking Git configuration..."
|
||||
if git rev-parse --git-dir > /dev/null 2>&1; then
|
||||
echo " ✅ Git repository detected"
|
||||
|
||||
# Check remote
|
||||
if git remote -v | grep -q origin; then
|
||||
remote_url=$(git remote get-url origin)
|
||||
echo " ✅ Remote configured: $remote_url"
|
||||
|
||||
# Check if remote is the CCPM template repository
|
||||
if [[ "$remote_url" == *"automazeio/ccpm"* ]] || [[ "$remote_url" == *"automazeio/ccpm.git"* ]]; then
|
||||
echo ""
|
||||
echo " ⚠️ WARNING: Your remote origin points to the CCPM template repository!"
|
||||
echo " This means any issues you create will go to the template repo, not your project."
|
||||
echo ""
|
||||
echo " To fix this:"
|
||||
echo " 1. Fork the repository or create your own on GitHub"
|
||||
echo " 2. Update your remote:"
|
||||
echo " git remote set-url origin https://github.com/YOUR_USERNAME/YOUR_REPO.git"
|
||||
echo ""
|
||||
else
|
||||
# Create GitHub labels if this is a GitHub repository
|
||||
if gh repo view &> /dev/null; then
|
||||
echo ""
|
||||
echo "🏷️ Creating GitHub labels..."
|
||||
|
||||
# Create base labels with improved error handling
|
||||
epic_created=false
|
||||
task_created=false
|
||||
|
||||
if gh label create "epic" --color "0E8A16" --description "Epic issue containing multiple related tasks" --force 2>/dev/null; then
|
||||
epic_created=true
|
||||
elif gh label list 2>/dev/null | grep -q "^epic"; then
|
||||
epic_created=true # Label already exists
|
||||
fi
|
||||
|
||||
if gh label create "task" --color "1D76DB" --description "Individual task within an epic" --force 2>/dev/null; then
|
||||
task_created=true
|
||||
elif gh label list 2>/dev/null | grep -q "^task"; then
|
||||
task_created=true # Label already exists
|
||||
fi
|
||||
|
||||
# Report results
|
||||
if $epic_created && $task_created; then
|
||||
echo " ✅ GitHub labels created (epic, task)"
|
||||
elif $epic_created || $task_created; then
|
||||
echo " ⚠️ Some GitHub labels created (epic: $epic_created, task: $task_created)"
|
||||
else
|
||||
echo " ❌ Could not create GitHub labels (check repository permissions)"
|
||||
fi
|
||||
else
|
||||
echo " ℹ️ Not a GitHub repository - skipping label creation"
|
||||
fi
|
||||
fi
|
||||
else
|
||||
echo " ⚠️ No remote configured"
|
||||
echo " Add with: git remote add origin <url>"
|
||||
fi
|
||||
else
|
||||
echo " ⚠️ Not a git repository"
|
||||
echo " Initialize with: git init"
|
||||
fi
|
||||
|
||||
# Create CLAUDE.md if it doesn't exist
|
||||
if [ ! -f "CLAUDE.md" ]; then
|
||||
echo ""
|
||||
echo "📄 Creating CLAUDE.md..."
|
||||
cat > CLAUDE.md << 'EOF'
|
||||
# CLAUDE.md
|
||||
|
||||
> Think carefully and implement the most concise solution that changes as little code as possible.
|
||||
|
||||
## Project-Specific Instructions
|
||||
|
||||
Add your project-specific instructions here.
|
||||
|
||||
## Testing
|
||||
|
||||
Always run tests before committing:
|
||||
- `npm test` or equivalent for your stack
|
||||
|
||||
## Code Style
|
||||
|
||||
Follow existing patterns in the codebase.
|
||||
EOF
|
||||
echo " ✅ CLAUDE.md created"
|
||||
fi
|
||||
|
||||
# Summary
|
||||
echo ""
|
||||
echo "✅ Initialization Complete!"
|
||||
echo "=========================="
|
||||
echo ""
|
||||
echo "📊 System Status:"
|
||||
gh --version | head -1
|
||||
echo " Extensions: $(gh extension list | wc -l) installed"
|
||||
echo " Auth: $(gh auth status 2>&1 | grep -o 'Logged in to [^ ]*' || echo 'Not authenticated')"
|
||||
echo ""
|
||||
echo "🎯 Next Steps:"
|
||||
echo " 1. Create your first PRD: /pm:prd-new <feature-name>"
|
||||
echo " 2. View help: /pm:help"
|
||||
echo " 3. Check status: /pm:status"
|
||||
echo ""
|
||||
echo "📚 Documentation: README.md"
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,61 @@
|
||||
#!/bin/bash
|
||||
echo "Getting status..."
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
echo "📋 Next Available Tasks"
|
||||
echo "======================="
|
||||
echo ""
|
||||
|
||||
# Find tasks that are open and have no dependencies or whose dependencies are closed
|
||||
found=0
|
||||
|
||||
for epic_dir in .claude/epics/*/; do
|
||||
[ -d "$epic_dir" ] || continue
|
||||
epic_name=$(basename "$epic_dir")
|
||||
|
||||
for task_file in "$epic_dir"/[0-9]*.md; do
|
||||
[ -f "$task_file" ] || continue
|
||||
|
||||
# Check if task is open
|
||||
status=$(grep "^status:" "$task_file" | head -1 | sed 's/^status: *//')
|
||||
if [ "$status" != "open" ] && [ -n "$status" ]; then
|
||||
continue
|
||||
fi
|
||||
|
||||
# Check dependencies
|
||||
deps_line=$(grep "^depends_on:" "$task_file" | head -1)
|
||||
if [ -n "$deps_line" ]; then
|
||||
deps=$(echo "$deps_line" | sed 's/^depends_on: *//' | sed 's/^\[//' | sed 's/\]$//' | sed 's/^[[:space:]]*//' | sed 's/[[:space:]]*$//')
|
||||
[ -z "$deps" ] && deps=""
|
||||
else
|
||||
deps=""
|
||||
fi
|
||||
|
||||
# If no dependencies or empty, task is available
|
||||
if [ -z "$deps" ] || [ "$deps" = "depends_on:" ]; then
|
||||
task_name=$(grep "^name:" "$task_file" | head -1 | sed 's/^name: *//')
|
||||
task_num=$(basename "$task_file" .md)
|
||||
parallel=$(grep "^parallel:" "$task_file" | head -1 | sed 's/^parallel: *//')
|
||||
|
||||
echo "✅ Ready: #$task_num - $task_name"
|
||||
echo " Epic: $epic_name"
|
||||
[ "$parallel" = "true" ] && echo " 🔄 Can run in parallel"
|
||||
echo ""
|
||||
((found++))
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
if [ $found -eq 0 ]; then
|
||||
echo "No available tasks found."
|
||||
echo ""
|
||||
echo "💡 Suggestions:"
|
||||
echo " • Check blocked tasks: /pm:blocked"
|
||||
echo " • View all tasks: /pm:epic-list"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "📊 Summary: $found tasks ready to start"
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,89 @@
|
||||
# !/bin/bash
|
||||
# Check if PRD directory exists
|
||||
if [ ! -d ".claude/prds" ]; then
|
||||
echo "📁 No PRD directory found. Create your first PRD with: /pm:prd-new <feature-name>"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Check for PRD files
|
||||
if ! ls .claude/prds/*.md >/dev/null 2>&1; then
|
||||
echo "📁 No PRDs found. Create your first PRD with: /pm:prd-new <feature-name>"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Initialize counters
|
||||
backlog_count=0
|
||||
in_progress_count=0
|
||||
implemented_count=0
|
||||
total_count=0
|
||||
|
||||
echo "Getting PRDs..."
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
|
||||
echo "📋 PRD List"
|
||||
echo "==========="
|
||||
echo ""
|
||||
|
||||
# Display by status groups
|
||||
echo "🔍 Backlog PRDs:"
|
||||
for file in .claude/prds/*.md; do
|
||||
[ -f "$file" ] || continue
|
||||
status=$(grep "^status:" "$file" | head -1 | sed 's/^status: *//')
|
||||
if [ "$status" = "backlog" ] || [ "$status" = "draft" ] || [ -z "$status" ]; then
|
||||
name=$(grep "^name:" "$file" | head -1 | sed 's/^name: *//')
|
||||
desc=$(grep "^description:" "$file" | head -1 | sed 's/^description: *//')
|
||||
[ -z "$name" ] && name=$(basename "$file" .md)
|
||||
[ -z "$desc" ] && desc="No description"
|
||||
# echo " 📋 $name - $desc"
|
||||
echo " 📋 $file - $desc"
|
||||
((backlog_count++))
|
||||
fi
|
||||
((total_count++))
|
||||
done
|
||||
[ $backlog_count -eq 0 ] && echo " (none)"
|
||||
|
||||
echo ""
|
||||
echo "🔄 In-Progress PRDs:"
|
||||
for file in .claude/prds/*.md; do
|
||||
[ -f "$file" ] || continue
|
||||
status=$(grep "^status:" "$file" | head -1 | sed 's/^status: *//')
|
||||
if [ "$status" = "in-progress" ] || [ "$status" = "active" ]; then
|
||||
name=$(grep "^name:" "$file" | head -1 | sed 's/^name: *//')
|
||||
desc=$(grep "^description:" "$file" | head -1 | sed 's/^description: *//')
|
||||
[ -z "$name" ] && name=$(basename "$file" .md)
|
||||
[ -z "$desc" ] && desc="No description"
|
||||
# echo " 📋 $name - $desc"
|
||||
echo " 📋 $file - $desc"
|
||||
((in_progress_count++))
|
||||
fi
|
||||
done
|
||||
[ $in_progress_count -eq 0 ] && echo " (none)"
|
||||
|
||||
echo ""
|
||||
echo "✅ Implemented PRDs:"
|
||||
for file in .claude/prds/*.md; do
|
||||
[ -f "$file" ] || continue
|
||||
status=$(grep "^status:" "$file" | head -1 | sed 's/^status: *//')
|
||||
if [ "$status" = "implemented" ] || [ "$status" = "completed" ] || [ "$status" = "done" ]; then
|
||||
name=$(grep "^name:" "$file" | head -1 | sed 's/^name: *//')
|
||||
desc=$(grep "^description:" "$file" | head -1 | sed 's/^description: *//')
|
||||
[ -z "$name" ] && name=$(basename "$file" .md)
|
||||
[ -z "$desc" ] && desc="No description"
|
||||
# echo " 📋 $name - $desc"
|
||||
echo " 📋 $file - $desc"
|
||||
((implemented_count++))
|
||||
fi
|
||||
done
|
||||
[ $implemented_count -eq 0 ] && echo " (none)"
|
||||
|
||||
# Display summary
|
||||
echo ""
|
||||
echo "📊 PRD Summary"
|
||||
echo " Total PRDs: $total_count"
|
||||
echo " Backlog: $backlog_count"
|
||||
echo " In-Progress: $in_progress_count"
|
||||
echo " Implemented: $implemented_count"
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "📄 PRD Status Report"
|
||||
echo "===================="
|
||||
echo ""
|
||||
|
||||
if [ ! -d ".claude/prds" ]; then
|
||||
echo "No PRD directory found."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
total=$(ls .claude/prds/*.md 2>/dev/null | wc -l)
|
||||
[ $total -eq 0 ] && echo "No PRDs found." && exit 0
|
||||
|
||||
# Count by status
|
||||
backlog=0
|
||||
in_progress=0
|
||||
implemented=0
|
||||
|
||||
for file in .claude/prds/*.md; do
|
||||
[ -f "$file" ] || continue
|
||||
status=$(grep "^status:" "$file" | head -1 | sed 's/^status: *//')
|
||||
|
||||
case "$status" in
|
||||
backlog|draft|"") ((backlog++)) ;;
|
||||
in-progress|active) ((in_progress++)) ;;
|
||||
implemented|completed|done) ((implemented++)) ;;
|
||||
*) ((backlog++)) ;;
|
||||
esac
|
||||
done
|
||||
|
||||
echo "Getting status..."
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
# Display chart
|
||||
echo "📊 Distribution:"
|
||||
echo "================"
|
||||
|
||||
echo ""
|
||||
echo " Backlog: $(printf '%-3d' $backlog) [$(printf '%0.s█' $(seq 1 $((backlog*20/total))))]"
|
||||
echo " In Progress: $(printf '%-3d' $in_progress) [$(printf '%0.s█' $(seq 1 $((in_progress*20/total))))]"
|
||||
echo " Implemented: $(printf '%-3d' $implemented) [$(printf '%0.s█' $(seq 1 $((implemented*20/total))))]"
|
||||
echo ""
|
||||
echo " Total PRDs: $total"
|
||||
|
||||
# Recent activity
|
||||
echo ""
|
||||
echo "📅 Recent PRDs (last 5 modified):"
|
||||
ls -t .claude/prds/*.md 2>/dev/null | head -5 | while read file; do
|
||||
name=$(grep "^name:" "$file" | head -1 | sed 's/^name: *//')
|
||||
[ -z "$name" ] && name=$(basename "$file" .md)
|
||||
echo " • $name"
|
||||
done
|
||||
|
||||
# Suggestions
|
||||
echo ""
|
||||
echo "💡 Next Actions:"
|
||||
[ $backlog -gt 0 ] && echo " • Parse backlog PRDs to epics: /pm:prd-parse <name>"
|
||||
[ $in_progress -gt 0 ] && echo " • Check progress on active PRDs: /pm:epic-status <name>"
|
||||
[ $total -eq 0 ] && echo " • Create your first PRD: /pm:prd-new <name>"
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/bin/bash
|
||||
|
||||
query="$1"
|
||||
|
||||
if [ -z "$query" ]; then
|
||||
echo "❌ Please provide a search query"
|
||||
echo "Usage: /pm:search <query>"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Searching for '$query'..."
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
echo "🔍 Search results for: '$query'"
|
||||
echo "================================"
|
||||
echo ""
|
||||
|
||||
# Search in PRDs
|
||||
if [ -d ".claude/prds" ]; then
|
||||
echo "📄 PRDs:"
|
||||
results=$(grep -l -i "$query" .claude/prds/*.md 2>/dev/null)
|
||||
if [ -n "$results" ]; then
|
||||
for file in $results; do
|
||||
name=$(basename "$file" .md)
|
||||
matches=$(grep -c -i "$query" "$file")
|
||||
echo " • $name ($matches matches)"
|
||||
done
|
||||
else
|
||||
echo " No matches"
|
||||
fi
|
||||
echo ""
|
||||
fi
|
||||
|
||||
# Search in Epics
|
||||
if [ -d ".claude/epics" ]; then
|
||||
echo "📚 Epics:"
|
||||
results=$(find .claude/epics -name "epic.md" -exec grep -l -i "$query" {} \; 2>/dev/null)
|
||||
if [ -n "$results" ]; then
|
||||
for file in $results; do
|
||||
epic_name=$(basename $(dirname "$file"))
|
||||
matches=$(grep -c -i "$query" "$file")
|
||||
echo " • $epic_name ($matches matches)"
|
||||
done
|
||||
else
|
||||
echo " No matches"
|
||||
fi
|
||||
echo ""
|
||||
fi
|
||||
|
||||
# Search in Tasks
|
||||
if [ -d ".claude/epics" ]; then
|
||||
echo "📝 Tasks:"
|
||||
results=$(find .claude/epics -name "[0-9]*.md" -exec grep -l -i "$query" {} \; 2>/dev/null | head -10)
|
||||
if [ -n "$results" ]; then
|
||||
for file in $results; do
|
||||
epic_name=$(basename $(dirname "$file"))
|
||||
task_num=$(basename "$file" .md)
|
||||
echo " • Task #$task_num in $epic_name"
|
||||
done
|
||||
else
|
||||
echo " No matches"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Summary
|
||||
total=$(find .claude -name "*.md" -exec grep -l -i "$query" {} \; 2>/dev/null | wc -l)
|
||||
echo ""
|
||||
echo "📊 Total files with matches: $total"
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "📅 Daily Standup - $(date '+%Y-%m-%d')"
|
||||
echo "================================"
|
||||
echo ""
|
||||
|
||||
today=$(date '+%Y-%m-%d')
|
||||
|
||||
echo "Getting status..."
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
echo "📝 Today's Activity:"
|
||||
echo "===================="
|
||||
echo ""
|
||||
|
||||
# Find files modified today
|
||||
recent_files=$(find .claude -name "*.md" -mtime -1 2>/dev/null)
|
||||
|
||||
if [ -n "$recent_files" ]; then
|
||||
# Count by type
|
||||
prd_count=$(echo "$recent_files" | grep -c "/prds/" 2>/dev/null | tr -d '[:space:]')
|
||||
epic_count=$(echo "$recent_files" | grep -c "/epic.md" 2>/dev/null | tr -d '[:space:]')
|
||||
task_count=$(echo "$recent_files" | grep -c "/[0-9]*.md" 2>/dev/null | tr -d '[:space:]')
|
||||
update_count=$(echo "$recent_files" | grep -c "/updates/" 2>/dev/null | tr -d '[:space:]')
|
||||
prd_count=${prd_count:-0}; epic_count=${epic_count:-0}; task_count=${task_count:-0}; update_count=${update_count:-0}
|
||||
|
||||
[ "$prd_count" -gt 0 ] && echo " • Modified $prd_count PRD(s)"
|
||||
[ "$epic_count" -gt 0 ] && echo " • Updated $epic_count epic(s)"
|
||||
[ "$task_count" -gt 0 ] && echo " • Worked on $task_count task(s)"
|
||||
[ "$update_count" -gt 0 ] && echo " • Posted $update_count progress update(s)"
|
||||
else
|
||||
echo " No activity recorded today"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "🔄 Currently In Progress:"
|
||||
# Show active work items
|
||||
for updates_dir in .claude/epics/*/updates/*/; do
|
||||
[ -d "$updates_dir" ] || continue
|
||||
if [ -f "$updates_dir/progress.md" ]; then
|
||||
issue_num=$(basename "$updates_dir")
|
||||
epic_name=$(basename $(dirname $(dirname "$updates_dir")))
|
||||
completion=$(grep "^completion:" "$updates_dir/progress.md" | head -1 | sed 's/^completion: *//')
|
||||
echo " • Issue #$issue_num ($epic_name) - ${completion:-0%} complete"
|
||||
fi
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "⏭️ Next Available Tasks:"
|
||||
# Show top 3 available tasks
|
||||
count=0
|
||||
for epic_dir in .claude/epics/*/; do
|
||||
[ -d "$epic_dir" ] || continue
|
||||
for task_file in "$epic_dir"/[0-9]*.md; do
|
||||
[ -f "$task_file" ] || continue
|
||||
status=$(grep "^status:" "$task_file" | head -1 | sed 's/^status: *//')
|
||||
if [ "$status" != "open" ] && [ -n "$status" ]; then
|
||||
continue
|
||||
fi
|
||||
|
||||
deps_line=$(grep "^depends_on:" "$task_file" | head -1)
|
||||
if [ -n "$deps_line" ]; then
|
||||
deps=$(echo "$deps_line" | sed 's/^depends_on: *//' | sed 's/^\[//' | sed 's/\]$//' | sed 's/^[[:space:]]*//' | sed 's/[[:space:]]*$//')
|
||||
[ -z "$deps" ] && deps=""
|
||||
else
|
||||
deps=""
|
||||
fi
|
||||
if [ -z "$deps" ] || [ "$deps" = "depends_on:" ]; then
|
||||
task_name=$(grep "^name:" "$task_file" | head -1 | sed 's/^name: *//')
|
||||
task_num=$(basename "$task_file" .md)
|
||||
echo " • #$task_num - $task_name"
|
||||
((count++))
|
||||
[ $count -ge 3 ] && break 2
|
||||
fi
|
||||
done
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "📊 Quick Stats:"
|
||||
total_tasks=$(find .claude/epics -name "[0-9]*.md" 2>/dev/null | wc -l)
|
||||
open_tasks=$(find .claude/epics -name "[0-9]*.md" -exec grep -l "^status: *open" {} \; 2>/dev/null | wc -l)
|
||||
closed_tasks=$(find .claude/epics -name "[0-9]*.md" -exec grep -l "^status: *closed" {} \; 2>/dev/null | wc -l)
|
||||
echo " Tasks: $open_tasks open, $closed_tasks closed, $total_tasks total"
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "Getting status..."
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
|
||||
echo "📊 Project Status"
|
||||
echo "================"
|
||||
echo ""
|
||||
|
||||
echo "📄 PRDs:"
|
||||
if [ -d ".claude/prds" ]; then
|
||||
total=$(ls .claude/prds/*.md 2>/dev/null | wc -l)
|
||||
echo " Total: $total"
|
||||
else
|
||||
echo " No PRDs found"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "📚 Epics:"
|
||||
if [ -d ".claude/epics" ]; then
|
||||
total=$(ls -d .claude/epics/*/ 2>/dev/null | grep -v '/archived/$' | wc -l)
|
||||
echo " Total: $total"
|
||||
else
|
||||
echo " No epics found"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "📝 Tasks:"
|
||||
if [ -d ".claude/epics" ]; then
|
||||
total=$(find .claude/epics -path "*/archived/*" -prune -o -name "[0-9]*.md" -print 2>/dev/null | wc -l)
|
||||
open=$(find .claude/epics -path "*/archived/*" -prune -o -name "[0-9]*.md" -print 2>/dev/null | xargs grep -l "^status: *open" 2>/dev/null | wc -l)
|
||||
closed=$(find .claude/epics -path "*/archived/*" -prune -o -name "[0-9]*.md" -print 2>/dev/null | xargs grep -l "^status: *closed" 2>/dev/null | wc -l)
|
||||
echo " Open: $open"
|
||||
echo " Closed: $closed"
|
||||
echo " Total: $total"
|
||||
else
|
||||
echo " No tasks found"
|
||||
fi
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "Validating PM System..."
|
||||
echo ""
|
||||
echo ""
|
||||
|
||||
echo "🔍 Validating PM System"
|
||||
echo "======================="
|
||||
echo ""
|
||||
|
||||
errors=0
|
||||
warnings=0
|
||||
|
||||
# Check directory structure
|
||||
echo "📁 Directory Structure:"
|
||||
[ -d ".claude" ] && echo " ✅ .claude directory exists" || { echo " ❌ .claude directory missing"; ((errors++)); }
|
||||
[ -d ".claude/prds" ] && echo " ✅ PRDs directory exists" || echo " ⚠️ PRDs directory missing"
|
||||
[ -d ".claude/epics" ] && echo " ✅ Epics directory exists" || echo " ⚠️ Epics directory missing"
|
||||
[ -d ".claude/rules" ] && echo " ✅ Rules directory exists" || echo " ⚠️ Rules directory missing"
|
||||
echo ""
|
||||
|
||||
# Check for orphaned files
|
||||
echo "🗂️ Data Integrity:"
|
||||
|
||||
# Check epics have epic.md files
|
||||
for epic_dir in .claude/epics/*/; do
|
||||
[ -d "$epic_dir" ] || continue
|
||||
if [ ! -f "$epic_dir/epic.md" ]; then
|
||||
echo " ⚠️ Missing epic.md in $(basename "$epic_dir")"
|
||||
((warnings++))
|
||||
fi
|
||||
done
|
||||
|
||||
# Check for tasks without epics
|
||||
orphaned=$(find .claude -name "[0-9]*.md" -not -path ".claude/epics/*/*" 2>/dev/null | wc -l)
|
||||
[ $orphaned -gt 0 ] && echo " ⚠️ Found $orphaned orphaned task files" && ((warnings++))
|
||||
|
||||
# Check for broken references
|
||||
echo ""
|
||||
echo "🔗 Reference Check:"
|
||||
|
||||
for task_file in .claude/epics/*/[0-9]*.md; do
|
||||
[ -f "$task_file" ] || continue
|
||||
|
||||
deps_line=$(grep "^depends_on:" "$task_file" | head -1)
|
||||
if [ -n "$deps_line" ]; then
|
||||
deps=$(echo "$deps_line" | sed 's/^depends_on: *//' | sed 's/^\[//' | sed 's/\]$//' | sed 's/,/ /g' | sed 's/^[[:space:]]*//' | sed 's/[[:space:]]*$//')
|
||||
[ -z "$deps" ] && deps=""
|
||||
else
|
||||
deps=""
|
||||
fi
|
||||
if [ -n "$deps" ] && [ "$deps" != "depends_on:" ]; then
|
||||
epic_dir=$(dirname "$task_file")
|
||||
for dep in $deps; do
|
||||
if [ ! -f "$epic_dir/$dep.md" ]; then
|
||||
echo " ⚠️ Task $(basename "$task_file" .md) references missing task: $dep"
|
||||
((warnings++))
|
||||
fi
|
||||
done
|
||||
fi
|
||||
done
|
||||
|
||||
if [ $warnings -eq 0 ] && [ $errors -eq 0 ]; then
|
||||
echo " ✅ All references valid"
|
||||
fi
|
||||
|
||||
# Check frontmatter
|
||||
echo ""
|
||||
echo "📝 Frontmatter Validation:"
|
||||
invalid=0
|
||||
|
||||
for file in $(find .claude -name "*.md" -path "*/epics/*" -o -path "*/prds/*" 2>/dev/null); do
|
||||
if ! grep -q "^---" "$file"; then
|
||||
echo " ⚠️ Missing frontmatter: $(basename "$file")"
|
||||
((invalid++))
|
||||
fi
|
||||
done
|
||||
|
||||
[ $invalid -eq 0 ] && echo " ✅ All files have frontmatter"
|
||||
|
||||
# Summary
|
||||
echo ""
|
||||
echo "📊 Validation Summary:"
|
||||
echo " Errors: $errors"
|
||||
echo " Warnings: $warnings"
|
||||
echo " Invalid files: $invalid"
|
||||
|
||||
if [ $errors -eq 0 ] && [ $warnings -eq 0 ] && [ $invalid -eq 0 ]; then
|
||||
echo ""
|
||||
echo "✅ System is healthy!"
|
||||
else
|
||||
echo ""
|
||||
echo "💡 Run /pm:clean to fix some issues automatically"
|
||||
fi
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,111 @@
|
||||
# Structure — Break Down an Epic
|
||||
|
||||
This phase converts a technical epic into concrete, numbered task files with dependency and parallelization metadata.
|
||||
|
||||
---
|
||||
|
||||
## Epic Decomposition
|
||||
|
||||
**Trigger**: User wants to break an epic into actionable tasks.
|
||||
|
||||
### Preflight
|
||||
|
||||
- Verify `.claude/epics/<name>/epic.md` exists with valid frontmatter.
|
||||
- If numbered task files (001.md, 002.md...) already exist in the epic directory, list them and confirm deletion before recreating.
|
||||
- If epic status is "completed", warn the user before proceeding.
|
||||
|
||||
### Process
|
||||
|
||||
Read the epic fully. Analyze for parallelism — which pieces of work can happen simultaneously without file conflicts?
|
||||
|
||||
**Task types to consider:**
|
||||
|
||||
- Setup: environment, scaffolding, dependencies
|
||||
- Data: models, schemas, migrations
|
||||
- API: endpoints, services, integration
|
||||
- UI: components, pages, styling
|
||||
- Tests: unit, integration, e2e
|
||||
- Docs: README, API docs, changelogs
|
||||
|
||||
**Parallelization strategy by epic size:**
|
||||
|
||||
- Small (<5 tasks): create sequentially
|
||||
- Medium (5–10 tasks): batch into 2–3 groups, spawn parallel Task agents
|
||||
- Large (>10 tasks): analyze dependencies first, launch parallel agents (max 5 concurrent), create dependent tasks after prerequisites
|
||||
|
||||
For parallel creation, use the Task tool:
|
||||
|
||||
```yaml
|
||||
Task:
|
||||
description: "Create task files batch N"
|
||||
subagent_type: "general-purpose"
|
||||
prompt: |
|
||||
Create task files for epic: <name>
|
||||
Tasks to create: [list 3-4 tasks]
|
||||
Save to: .claude/epics/<name>/001.md, 002.md, etc.
|
||||
Follow the task file format exactly.
|
||||
Return: list of files created.
|
||||
```
|
||||
|
||||
### Task File Format
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: <Task Title>
|
||||
status: open
|
||||
created: <run: date -u +"%Y-%m-%dT%H:%M:%SZ">
|
||||
updated: <same as created>
|
||||
github: (will be set on sync)
|
||||
depends_on: []
|
||||
parallel: true
|
||||
conflicts_with: []
|
||||
---
|
||||
|
||||
# Task: <Task Title>
|
||||
|
||||
## Description
|
||||
|
||||
## Acceptance Criteria
|
||||
- [ ]
|
||||
|
||||
## Technical Details
|
||||
|
||||
## Dependencies
|
||||
|
||||
## Effort Estimate
|
||||
- Size: XS/S/M/L/XL
|
||||
- Hours: N
|
||||
|
||||
## Definition of Done
|
||||
- [ ] Code implemented
|
||||
- [ ] Tests written and passing
|
||||
- [ ] Code reviewed
|
||||
```
|
||||
|
||||
**Numbering**: sequential 001.md, 002.md, etc. Tasks are renamed to GitHub issue numbers after sync — do not hard-code dependencies by filename, use the `depends_on` array.
|
||||
|
||||
### After Creating All Tasks
|
||||
|
||||
Append a summary to the epic file:
|
||||
|
||||
```markdown
|
||||
## Tasks Created
|
||||
- [ ] 001.md - <Title> (parallel: true/false)
|
||||
- [ ] 002.md - <Title> (parallel: true/false)
|
||||
|
||||
Total tasks: N
|
||||
Parallel tasks: N
|
||||
Sequential tasks: N
|
||||
Estimated total effort: N hours
|
||||
```
|
||||
|
||||
**After completion**: Confirm "✅ Created N tasks for epic: <name>" and suggest: "Ready to push to GitHub? Say: sync the <name> epic"
|
||||
|
||||
---
|
||||
|
||||
## Dependency Rules
|
||||
|
||||
- `depends_on` lists task numbers that must complete before this task can start.
|
||||
- `parallel: true` means the task can run concurrently with others it doesn't conflict with.
|
||||
- `conflicts_with` lists tasks that touch the same files — these cannot run in parallel.
|
||||
- Circular dependencies are an error — check before finalizing.
|
||||
@@ -0,0 +1,315 @@
|
||||
# Sync — Push to GitHub & Track Progress
|
||||
|
||||
This phase covers pushing local epics/tasks to GitHub as issues, syncing progress as comments, and closing issues when work is done.
|
||||
|
||||
---
|
||||
|
||||
## Repository Safety Check
|
||||
|
||||
**Always run this before any GitHub write operation:**
|
||||
|
||||
```bash
|
||||
remote_url=$(git remote get-url origin 2>/dev/null || echo "")
|
||||
if [[ "$remote_url" == *"automazeio/ccpm"* ]]; then
|
||||
echo "❌ Cannot sync to the CCPM template repository."
|
||||
echo "Update remote: git remote set-url origin https://github.com/YOUR/REPO.git"
|
||||
exit 1
|
||||
fi
|
||||
REPO=$(echo "$remote_url" | sed 's|.*github.com[:/]||' | sed 's|\.git$||')
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Epic Sync — Push Epic + Tasks to GitHub
|
||||
|
||||
**Trigger**: User wants to push a local epic and its tasks to GitHub as issues.
|
||||
|
||||
### Preflight
|
||||
|
||||
- Verify `.claude/epics/<name>/epic.md` exists.
|
||||
- Verify numbered task files exist — if none: "❌ No tasks to sync. Decompose the epic first."
|
||||
|
||||
### Process
|
||||
|
||||
**Step 1 — Create epic issue:**
|
||||
|
||||
Strip frontmatter from epic.md, then:
|
||||
|
||||
```bash
|
||||
sed '1,/^---$/d; 1,/^---$/d' .claude/epics/<name>/epic.md > /tmp/epic-body.md
|
||||
epic_number=$(gh issue create \
|
||||
--repo "$REPO" \
|
||||
--title "Epic: <name>" \
|
||||
--body-file /tmp/epic-body.md \
|
||||
--label "epic,epic:<name>,feature" \
|
||||
--json number -q .number)
|
||||
```
|
||||
|
||||
**Step 2 — Create task sub-issues:**
|
||||
|
||||
Check if `gh-sub-issue` extension is available:
|
||||
|
||||
```bash
|
||||
if gh extension list | grep -q "yahsan2/gh-sub-issue"; then
|
||||
use_subissues=true
|
||||
fi
|
||||
```
|
||||
|
||||
For <5 tasks: create sequentially.
|
||||
For ≥5 tasks: use parallel Task agents (3-4 tasks per batch).
|
||||
|
||||
Per task:
|
||||
|
||||
```bash
|
||||
sed '1,/^---$/d; 1,/^---$/d' <task_file> > /tmp/task-body.md
|
||||
task_number=$(gh issue create \
|
||||
--repo "$REPO" \
|
||||
--title "<task_name>" \
|
||||
--body-file /tmp/task-body.md \
|
||||
--label "task,epic:<name>" \
|
||||
--json number -q .number)
|
||||
# or with sub-issues:
|
||||
# gh sub-issue create --parent $epic_number ...
|
||||
```
|
||||
|
||||
**Step 3 — Rename task files and update references:**
|
||||
|
||||
After all issues are created, rename `001.md` → `<issue_number>.md` and update all `depends_on`/`conflicts_with` arrays to use real issue numbers (not sequential numbers).
|
||||
|
||||
```bash
|
||||
# Build old→new mapping, then for each task file:
|
||||
sed -i.bak "s/\b001\b/<new_num_1>/g" <file> # repeat for each mapping
|
||||
mv 001.md <new_num>.md
|
||||
```
|
||||
|
||||
**Step 4 — Update frontmatter:**
|
||||
|
||||
```bash
|
||||
current_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
|
||||
# Update github: and updated: fields in epic.md and each task file
|
||||
github_url="https://github.com/$REPO/issues/<number>"
|
||||
sed -i.bak "/^github:/c\\github: $github_url" <file>
|
||||
sed -i.bak "/^updated:/c\\updated: $current_date" <file>
|
||||
rm <file>.bak
|
||||
```
|
||||
|
||||
**Step 5 — Create worktree for the epic:**
|
||||
|
||||
```bash
|
||||
git checkout main && git pull origin main
|
||||
git worktree add ../epic-<name> -b epic/<name>
|
||||
```
|
||||
|
||||
**Step 6 — Create github-mapping.md:**
|
||||
|
||||
```markdown
|
||||
# GitHub Issue Mapping
|
||||
Epic: #<N> - https://github.com/<repo>/issues/<N>
|
||||
Tasks:
|
||||
- #<N>: <title> - https://github.com/<repo>/issues/<N>
|
||||
Synced: <datetime>
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
✅ Synced epic <name> to GitHub
|
||||
Epic: #<N>
|
||||
Tasks: N sub-issues
|
||||
Worktree: ../epic-<name>
|
||||
Next: "start working on issue <N>" or "start the <name> epic"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Issue Sync — Post Progress to GitHub
|
||||
|
||||
**Trigger**: User wants to sync local development progress to a GitHub issue as a comment.
|
||||
|
||||
### Preflight
|
||||
|
||||
- Verify issue exists: `gh issue view <N> --json state`
|
||||
- Check `.claude/epics/*/updates/<N>/` exists with a `progress.md` file.
|
||||
- Check `last_sync` in progress.md — if synced <5 minutes ago, confirm before proceeding.
|
||||
|
||||
### Process
|
||||
|
||||
Gather updates from `.claude/epics/<epic>/updates/<N>/` (progress.md, notes.md, commits.md).
|
||||
|
||||
Format and post a comment:
|
||||
|
||||
```bash
|
||||
gh issue comment <N> --body-file /tmp/update-comment.md
|
||||
```
|
||||
|
||||
Comment format:
|
||||
|
||||
```markdown
|
||||
## 🔄 Progress Update - <date>
|
||||
|
||||
### ✅ Completed Work
|
||||
### 🔄 In Progress
|
||||
### 📝 Technical Notes
|
||||
### 📊 Acceptance Criteria Status
|
||||
### 🚀 Next Steps
|
||||
### ⚠️ Blockers
|
||||
|
||||
---
|
||||
*Progress: N% | Synced at <timestamp>*
|
||||
```
|
||||
|
||||
After posting: update `last_sync` in progress.md frontmatter, update `updated` in the task file.
|
||||
|
||||
Add sync marker to local files to prevent duplicate comments:
|
||||
|
||||
```markdown
|
||||
<!-- SYNCED: <datetime> -->
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Closing an Issue
|
||||
|
||||
**Trigger**: User marks a task complete.
|
||||
|
||||
### Process
|
||||
|
||||
1. Find the local task file (`.claude/epics/*/<N>.md`).
|
||||
2. Update frontmatter: `status: closed`, `updated: <now>`.
|
||||
3. Post completion comment:
|
||||
|
||||
```bash
|
||||
echo "✅ Task completed — all acceptance criteria met." | gh issue comment <N> --body-file -
|
||||
gh issue close <N>
|
||||
```
|
||||
1. Check off the task in the epic issue body:
|
||||
|
||||
```bash
|
||||
gh issue view <epic_N> --json body -q .body > /tmp/epic-body.md
|
||||
sed -i "s/- \[ \] #<N>/- [x] #<N>/" /tmp/epic-body.md
|
||||
gh issue edit <epic_N> --body-file /tmp/epic-body.md
|
||||
```
|
||||
1. Recalculate and update epic progress: `progress = closed_tasks / total_tasks * 100`
|
||||
|
||||
---
|
||||
|
||||
## Merging an Epic
|
||||
|
||||
**Trigger**: User wants to merge a completed epic back to main.
|
||||
|
||||
### Preflight
|
||||
|
||||
- Verify worktree `../epic-<name>` exists.
|
||||
- Check for uncommitted changes in the worktree — block if dirty.
|
||||
- Warn if any task issues are still open.
|
||||
|
||||
### Process
|
||||
|
||||
```bash
|
||||
# From worktree: run project tests if detectable
|
||||
cd ../epic-<name>
|
||||
# detect and run: npm test / pytest / cargo test / go test / etc.
|
||||
|
||||
# From main repo:
|
||||
git checkout main && git pull origin main
|
||||
git merge epic/<name> --no-ff -m "Merge epic: <name>"
|
||||
git push origin main
|
||||
|
||||
# Cleanup
|
||||
git worktree remove ../epic-<name>
|
||||
git branch -d epic/<name>
|
||||
git push origin --delete epic/<name>
|
||||
|
||||
# Archive
|
||||
mkdir -p .claude/epics/archived/
|
||||
mv .claude/epics/<name> .claude/epics/archived/
|
||||
|
||||
# Close GitHub issues
|
||||
epic_issue=$(grep 'github:' .claude/epics/archived/<name>/epic.md | grep -oE '[0-9]+$')
|
||||
gh issue close $epic_issue -c "Epic completed and merged to main"
|
||||
```
|
||||
|
||||
Update epic.md frontmatter: `status: completed`.
|
||||
|
||||
---
|
||||
|
||||
## Reporting a Bug Against a Completed Issue
|
||||
|
||||
**Trigger**: User finds a bug while testing a completed or in-progress issue — e.g. "found a bug in issue 42", "email validation is broken, came up while testing issue 42".
|
||||
|
||||
The workflow should stay automated: create a linked bug task without losing context from the original issue.
|
||||
|
||||
### Process
|
||||
|
||||
**Step 1 — Read the original issue for context:**
|
||||
|
||||
```bash
|
||||
gh issue view <original_N> --json title,body,labels
|
||||
```
|
||||
|
||||
Also read the local task file if it exists: `.claude/epics/*/<original_N>.md`
|
||||
|
||||
**Step 2 — Create a local bug task file:**
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: Bug: <short description>
|
||||
status: open
|
||||
created: <run: date -u +"%Y-%m-%dT%H:%M:%SZ">
|
||||
updated: <same>
|
||||
github: (will be set on sync)
|
||||
depends_on: []
|
||||
parallel: false
|
||||
conflicts_with: []
|
||||
bug_for: <original_N>
|
||||
---
|
||||
|
||||
# Bug: <short description>
|
||||
|
||||
## Context
|
||||
Found while working on / testing issue #<original_N>: <original title>
|
||||
|
||||
## Description
|
||||
<what's broken>
|
||||
|
||||
## Steps to Reproduce
|
||||
<steps>
|
||||
|
||||
## Expected vs Actual
|
||||
- Expected:
|
||||
- Actual:
|
||||
|
||||
## Acceptance Criteria
|
||||
- [ ] Bug is fixed
|
||||
- [ ] Original issue #<original_N> behaviour is unaffected
|
||||
|
||||
## Effort Estimate
|
||||
- Size: XS/S
|
||||
```
|
||||
|
||||
Save to `.claude/epics/<same_epic_as_original>/bug-<original_N>-<slug>.md`
|
||||
|
||||
**Step 3 — Create a linked GitHub issue:**
|
||||
|
||||
```bash
|
||||
gh issue create \
|
||||
--repo "$REPO" \
|
||||
--title "Bug: <short description>" \
|
||||
--body "$(cat /tmp/bug-body.md)" \
|
||||
--label "bug,epic:<epic_name>" \
|
||||
--json number -q .number
|
||||
```
|
||||
|
||||
The issue body should open with `Fixes / follow-up to #<original_N>` so GitHub auto-links them.
|
||||
|
||||
**Step 4 — Update the local file** with the GitHub issue number and rename to `<new_N>.md`.
|
||||
|
||||
**Output:**
|
||||
|
||||
```
|
||||
✅ Bug issue created: #<new_N> — "Bug: <short description>"
|
||||
Linked to: #<original_N>
|
||||
Epic: <epic_name>
|
||||
|
||||
Start fixing it: "start working on issue <new_N>"
|
||||
```
|
||||
@@ -0,0 +1,165 @@
|
||||
# Track — Know Where Things Stand
|
||||
|
||||
Tracking operations use bash scripts directly for speed and consistency. The LLM is not needed for these — just run the script and present the output.
|
||||
|
||||
---
|
||||
|
||||
## Script-First Rule
|
||||
|
||||
All tracking operations have a corresponding bash script. Run the script; do not reconstruct the output manually.
|
||||
|
||||
Scripts live in `references/scripts/` relative to this skill, but need to run from the **project root** (where `.claude/` lives). Run them as:
|
||||
|
||||
```bash
|
||||
bash <skill_path>/references/scripts/<script>.sh [args]
|
||||
```
|
||||
|
||||
Or if ccpm is installed project-locally:
|
||||
|
||||
```bash
|
||||
bash ccpm/scripts/pm/<script>.sh [args]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Project Status
|
||||
|
||||
**Trigger**: "what's our status", "project status", "overview"
|
||||
|
||||
```bash
|
||||
bash references/scripts/status.sh
|
||||
```
|
||||
|
||||
Shows: active epics, open issues count, recent activity.
|
||||
|
||||
---
|
||||
|
||||
## Standup Report
|
||||
|
||||
**Trigger**: "standup", "daily standup", "what did we do", "morning update"
|
||||
|
||||
```bash
|
||||
bash references/scripts/standup.sh
|
||||
```
|
||||
|
||||
Shows: what was completed yesterday, what's in progress today, any blockers.
|
||||
|
||||
---
|
||||
|
||||
## List Epics
|
||||
|
||||
**Trigger**: "list epics", "show epics", "what epics do we have"
|
||||
|
||||
```bash
|
||||
bash references/scripts/epic-list.sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Show Epic Details
|
||||
|
||||
**Trigger**: "show the <name> epic", "epic details for <name>"
|
||||
|
||||
```bash
|
||||
bash references/scripts/epic-show.sh <name>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Epic Status
|
||||
|
||||
**Trigger**: "status of the <name> epic", "how far along is <name>"
|
||||
|
||||
```bash
|
||||
bash references/scripts/epic-status.sh <name>
|
||||
```
|
||||
|
||||
Shows: task completion breakdown, active agents, blocking issues.
|
||||
|
||||
---
|
||||
|
||||
## List PRDs
|
||||
|
||||
**Trigger**: "list PRDs", "what PRDs do we have", "show backlog"
|
||||
|
||||
```bash
|
||||
bash references/scripts/prd-list.sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## PRD Status
|
||||
|
||||
**Trigger**: "PRD status", "which PRDs are parsed", "what's in backlog"
|
||||
|
||||
```bash
|
||||
bash references/scripts/prd-status.sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Search
|
||||
|
||||
**Trigger**: "search for <query>", "find issues about <topic>", "look for <term>"
|
||||
|
||||
```bash
|
||||
bash references/scripts/search.sh "<query>"
|
||||
```
|
||||
|
||||
Searches local task files, PRDs, and epics for the query term.
|
||||
|
||||
---
|
||||
|
||||
## What's In Progress
|
||||
|
||||
**Trigger**: "what's in progress", "what are we working on", "active work"
|
||||
|
||||
```bash
|
||||
bash references/scripts/in-progress.sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## What's Next
|
||||
|
||||
**Trigger**: "what should I work on next", "what's next", "next priority"
|
||||
|
||||
```bash
|
||||
bash references/scripts/next.sh
|
||||
```
|
||||
|
||||
Shows highest-priority open tasks with no blocking dependencies.
|
||||
|
||||
---
|
||||
|
||||
## What's Blocked
|
||||
|
||||
**Trigger**: "what's blocked", "any blockers", "what can't we move on"
|
||||
|
||||
```bash
|
||||
bash references/scripts/blocked.sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Validate Project State
|
||||
|
||||
**Trigger**: "validate", "check project state", "is everything consistent"
|
||||
|
||||
```bash
|
||||
bash references/scripts/validate.sh
|
||||
```
|
||||
|
||||
Checks: frontmatter consistency, orphaned files, missing GitHub links, dependency integrity.
|
||||
|
||||
---
|
||||
|
||||
## When Scripts Fail
|
||||
|
||||
If a script fails or the output needs interpretation (e.g., an error in the output, or the user asks "what does this mean"), then step in to explain. But always run the script first — don't guess at what status/standup output would look like.
|
||||
|
||||
If `.claude/` directory doesn't exist at all, the project hasn't been initialized. Direct the user to run:
|
||||
|
||||
```bash
|
||||
bash references/scripts/init.sh
|
||||
```
|
||||
@@ -0,0 +1,224 @@
|
||||
---
|
||||
name: data-scientist
|
||||
description: Expert data scientist for advanced analytics, machine learning, and statistical modeling. Handles complex data analysis, predictive modeling, and business intelligence.
|
||||
---
|
||||
|
||||
## Use this skill when
|
||||
|
||||
- Working on data scientist tasks or workflows
|
||||
- Needing guidance, best practices, or checklists for data scientist
|
||||
|
||||
## Do not use this skill when
|
||||
|
||||
- The task is unrelated to data scientist
|
||||
- You need a different domain or tool outside this scope
|
||||
|
||||
## Instructions
|
||||
|
||||
- Clarify goals, constraints, and required inputs.
|
||||
- Apply relevant best practices and validate outcomes.
|
||||
- Provide actionable steps and verification.
|
||||
|
||||
You are a data scientist specializing in advanced analytics, machine learning, statistical modeling, and data-driven business insights.
|
||||
|
||||
## Purpose
|
||||
|
||||
Expert data scientist combining strong statistical foundations with modern machine learning techniques and business acumen. Masters the complete data science workflow from exploratory data analysis to production model deployment, with deep expertise in statistical methods, ML algorithms, and data visualization for actionable business insights.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### Statistical Analysis & Methodology
|
||||
|
||||
- Descriptive statistics, inferential statistics, and hypothesis testing
|
||||
- Experimental design: A/B testing, multivariate testing, randomized controlled trials
|
||||
- Causal inference: natural experiments, difference-in-differences, instrumental variables
|
||||
- Time series analysis: ARIMA, Prophet, seasonal decomposition, forecasting
|
||||
- Survival analysis and duration modeling for customer lifecycle analysis
|
||||
- Bayesian statistics and probabilistic modeling with PyMC3, Stan
|
||||
- Statistical significance testing, p-values, confidence intervals, effect sizes
|
||||
- Power analysis and sample size determination for experiments
|
||||
|
||||
### Machine Learning & Predictive Modeling
|
||||
|
||||
- Supervised learning: linear/logistic regression, decision trees, random forests, XGBoost, LightGBM
|
||||
- Unsupervised learning: clustering (K-means, hierarchical, DBSCAN), PCA, t-SNE, UMAP
|
||||
- Deep learning: neural networks, CNNs, RNNs, LSTMs, transformers with PyTorch/TensorFlow
|
||||
- Ensemble methods: bagging, boosting, stacking, voting classifiers
|
||||
- Model selection and hyperparameter tuning with cross-validation and Optuna
|
||||
- Feature engineering: selection, extraction, transformation, encoding categorical variables
|
||||
- Dimensionality reduction and feature importance analysis
|
||||
- Model interpretability: SHAP, LIME, feature attribution, partial dependence plots
|
||||
|
||||
### Data Analysis & Exploration
|
||||
|
||||
- Exploratory data analysis (EDA) with statistical summaries and visualizations
|
||||
- Data profiling: missing values, outliers, distributions, correlations
|
||||
- Univariate and multivariate analysis techniques
|
||||
- Cohort analysis and customer segmentation
|
||||
- Market basket analysis and association rule mining
|
||||
- Anomaly detection and fraud detection algorithms
|
||||
- Root cause analysis using statistical and ML approaches
|
||||
- Data storytelling and narrative building from analysis results
|
||||
|
||||
### Programming & Data Manipulation
|
||||
|
||||
- Python ecosystem: pandas, NumPy, scikit-learn, SciPy, statsmodels
|
||||
- R programming: dplyr, ggplot2, caret, tidymodels, shiny for statistical analysis
|
||||
- SQL for data extraction and analysis: window functions, CTEs, advanced joins
|
||||
- Big data processing: PySpark, Dask for distributed computing
|
||||
- Data wrangling: cleaning, transformation, merging, reshaping large datasets
|
||||
- Database interactions: PostgreSQL, MySQL, BigQuery, Snowflake, MongoDB
|
||||
- Version control and reproducible analysis with Git, Jupyter notebooks
|
||||
- Cloud platforms: AWS SageMaker, Azure ML, GCP Vertex AI
|
||||
|
||||
### Data Visualization & Communication
|
||||
|
||||
- Advanced plotting with matplotlib, seaborn, plotly, altair
|
||||
- Interactive dashboards with Streamlit, Dash, Shiny, Tableau, Power BI
|
||||
- Business intelligence visualization best practices
|
||||
- Statistical graphics: distribution plots, correlation matrices, regression diagnostics
|
||||
- Geographic data visualization and mapping with folium, geopandas
|
||||
- Real-time monitoring dashboards for model performance
|
||||
- Executive reporting and stakeholder communication
|
||||
- Data storytelling techniques for non-technical audiences
|
||||
|
||||
### Business Analytics & Domain Applications
|
||||
|
||||
#### Marketing Analytics
|
||||
|
||||
- Customer lifetime value (CLV) modeling and prediction
|
||||
- Attribution modeling: first-touch, last-touch, multi-touch attribution
|
||||
- Marketing mix modeling (MMM) for budget optimization
|
||||
- Campaign effectiveness measurement and incrementality testing
|
||||
- Customer segmentation and persona development
|
||||
- Recommendation systems for personalization
|
||||
- Churn prediction and retention modeling
|
||||
- Price elasticity and demand forecasting
|
||||
|
||||
#### Financial Analytics
|
||||
|
||||
- Credit risk modeling and scoring algorithms
|
||||
- Portfolio optimization and risk management
|
||||
- Fraud detection and anomaly monitoring systems
|
||||
- Algorithmic trading strategy development
|
||||
- Financial time series analysis and volatility modeling
|
||||
- Stress testing and scenario analysis
|
||||
- Regulatory compliance analytics (Basel, GDPR, etc.)
|
||||
- Market research and competitive intelligence analysis
|
||||
|
||||
#### Operations Analytics
|
||||
|
||||
- Supply chain optimization and demand planning
|
||||
- Inventory management and safety stock optimization
|
||||
- Quality control and process improvement using statistical methods
|
||||
- Predictive maintenance and equipment failure prediction
|
||||
- Resource allocation and capacity planning models
|
||||
- Network analysis and optimization problems
|
||||
- Simulation modeling for operational scenarios
|
||||
- Performance measurement and KPI development
|
||||
|
||||
### Advanced Analytics & Specialized Techniques
|
||||
|
||||
- Natural language processing: sentiment analysis, topic modeling, text classification
|
||||
- Computer vision: image classification, object detection, OCR applications
|
||||
- Graph analytics: network analysis, community detection, centrality measures
|
||||
- Reinforcement learning for optimization and decision making
|
||||
- Multi-armed bandits for online experimentation
|
||||
- Causal machine learning and uplift modeling
|
||||
- Synthetic data generation using GANs and VAEs
|
||||
- Federated learning for distributed model training
|
||||
|
||||
### Model Deployment & Productionization
|
||||
|
||||
- Model serialization and versioning with MLflow, DVC
|
||||
- REST API development for model serving with Flask, FastAPI
|
||||
- Batch prediction pipelines and real-time inference systems
|
||||
- Model monitoring: drift detection, performance degradation alerts
|
||||
- A/B testing frameworks for model comparison in production
|
||||
- Containerization with Docker for model deployment
|
||||
- Cloud deployment: AWS Lambda, Azure Functions, GCP Cloud Run
|
||||
- Model governance and compliance documentation
|
||||
|
||||
### Data Engineering for Analytics
|
||||
|
||||
- ETL/ELT pipeline development for analytics workflows
|
||||
- Data pipeline orchestration with Apache Airflow, Prefect
|
||||
- Feature stores for ML feature management and serving
|
||||
- Data quality monitoring and validation frameworks
|
||||
- Real-time data processing with Kafka, streaming analytics
|
||||
- Data warehouse design for analytics use cases
|
||||
- Data catalog and metadata management for discoverability
|
||||
- Performance optimization for analytical queries
|
||||
|
||||
### Experimental Design & Measurement
|
||||
|
||||
- Randomized controlled trials and quasi-experimental designs
|
||||
- Stratified randomization and block randomization techniques
|
||||
- Power analysis and minimum detectable effect calculations
|
||||
- Multiple hypothesis testing and false discovery rate control
|
||||
- Sequential testing and early stopping rules
|
||||
- Matched pairs analysis and propensity score matching
|
||||
- Difference-in-differences and synthetic control methods
|
||||
- Treatment effect heterogeneity and subgroup analysis
|
||||
|
||||
## Behavioral Traits
|
||||
|
||||
- Approaches problems with scientific rigor and statistical thinking
|
||||
- Balances statistical significance with practical business significance
|
||||
- Communicates complex analyses clearly to non-technical stakeholders
|
||||
- Validates assumptions and tests model robustness thoroughly
|
||||
- Focuses on actionable insights rather than just technical accuracy
|
||||
- Considers ethical implications and potential biases in analysis
|
||||
- Iterates quickly between hypotheses and data-driven validation
|
||||
- Documents methodology and ensures reproducible analysis
|
||||
- Stays current with statistical methods and ML advances
|
||||
- Collaborates effectively with business stakeholders and technical teams
|
||||
|
||||
## Knowledge Base
|
||||
|
||||
- Statistical theory and mathematical foundations of ML algorithms
|
||||
- Business domain knowledge across marketing, finance, and operations
|
||||
- Modern data science tools and their appropriate use cases
|
||||
- Experimental design principles and causal inference methods
|
||||
- Data visualization best practices for different audience types
|
||||
- Model evaluation metrics and their business interpretations
|
||||
- Cloud analytics platforms and their capabilities
|
||||
- Data ethics, bias detection, and fairness in ML
|
||||
- Storytelling techniques for data-driven presentations
|
||||
- Current trends in data science and analytics methodologies
|
||||
|
||||
## Response Approach
|
||||
|
||||
1. **Understand business context** and define clear analytical objectives
|
||||
2. **Explore data thoroughly** with statistical summaries and visualizations
|
||||
3. **Apply appropriate methods** based on data characteristics and business goals
|
||||
4. **Validate results rigorously** through statistical testing and cross-validation
|
||||
5. **Communicate findings clearly** with visualizations and actionable recommendations
|
||||
6. **Consider practical constraints** like data quality, timeline, and resources
|
||||
7. **Plan for implementation** including monitoring and maintenance requirements
|
||||
8. **Document methodology** for reproducibility and knowledge sharing
|
||||
|
||||
## Example Interactions
|
||||
|
||||
- "Analyze customer churn patterns and build a predictive model to identify at-risk customers"
|
||||
- "Design and analyze A/B test results for a new website feature with proper statistical testing"
|
||||
- "Perform market basket analysis to identify cross-selling opportunities in retail data"
|
||||
- "Build a demand forecasting model using time series analysis for inventory planning"
|
||||
- "Analyze the causal impact of marketing campaigns on customer acquisition"
|
||||
- "Create customer segmentation using clustering techniques and business metrics"
|
||||
- "Develop a recommendation system for e-commerce product suggestions"
|
||||
- "Investigate anomalies in financial transactions and build fraud detection models"
|
||||
|
||||
## Limitations
|
||||
|
||||
- Use this skill only when the task clearly matches the scope described above.
|
||||
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
|
||||
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
|
||||
|
||||
---
|
||||
|
||||
> **Provenance (A11 «ML / AI-разработка»):** vendored into Лидерра 2026-05-17 from
|
||||
> [`sickn33/antigravity-awesome-skills`](https://github.com/sickn33/antigravity-awesome-skills)
|
||||
> `skills/data-scientist`. Skill content is licensed **CC BY 4.0**; repository
|
||||
> tooling is MIT. Aggregator frontmatter (`risk`/`source`/`date_added`) dropped on
|
||||
> vendor. See `docs/ml/README.md` for the A11 toolset and boundaries.
|
||||
@@ -0,0 +1,142 @@
|
||||
---
|
||||
name: discovery-interview
|
||||
description: Структурированное интервью-discovery ПЕРЕД проектированием. Два режима. FEATURE — заказчик описывает проблему, боль или цель без готового решения («менеджеры жалуются на…», «сделки теряются», «хочу чтобы…»): JTBD-интервью вскрывает проблему до решения и отдаёт discovery-brief в brainstorming. SYSTEM — запрос ориентации по проекту («сориентируй», «где мы сейчас», «что в тулчейне / на карте», «catch-up по…»): синтез по мета-слою (карта, CLAUDE.md, MEMORY, Открытые_вопросы, Tooling, git log). SKIP — чёткий директив на реализацию («интегрируй X», «закрой находку Y», «поправь Z»): это не discovery. SKIP — анализ бизнес-процесса из кода или диагностика просадки измеримой метрики/конверсии («как устроен процесс X», «process discovery», «где узкое место», «почему просела конверсия»): это skill process-analysis. Используй при «discovery interview», «проведи discovery», «сориентируй по проекту» и при расплывчатом проблемном запросе, даже если слово «discovery» не названо.
|
||||
---
|
||||
|
||||
# Discovery Interview
|
||||
|
||||
Структурированное интервью, которое вскрывает **проблему** прежде, чем кто-либо
|
||||
начнёт проектировать решение. Два режима — FEATURE (интервью заказчика перед
|
||||
фичей) и SYSTEM (интервью-ориентация по состоянию проекта).
|
||||
|
||||
Зачем скил существует: запрос вида «менеджеры жалуются на X» или «хочу, чтобы Y» —
|
||||
это симптом, не задача. Уйдёшь сразу в дизайн — спроектируешь решение не той
|
||||
проблемы. Discovery interview удерживает разговор в проблемном поле ровно столько,
|
||||
сколько нужно, чтобы понять *настоящую* потребность, и только потом передаёт
|
||||
эстафету проектированию.
|
||||
|
||||
## Когда какой режим
|
||||
|
||||
| Запрос | Действие |
|
||||
|---|---|
|
||||
| Заказчик описал проблему / боль / цель без решения | режим **FEATURE** |
|
||||
| Заказчик просит сориентировать по проекту | режим **SYSTEM** |
|
||||
| Заказчик дал чёткий директив («сделай X», «интегрируй Y») | скил не нужен — работай напрямую |
|
||||
| Вопрос про устройство бизнес-процесса из кода | скил `process-analysis`, не этот |
|
||||
|
||||
## Несущий принцип — три слоя-источника
|
||||
|
||||
Этот скил соседствует со скилом `process-analysis` (раздел C10 карты). Чтобы не
|
||||
дублировать его, способности разведены по **слою данных**, с которым работают:
|
||||
|
||||
| Способность | Слой-источник | Метод |
|
||||
|---|---|---|
|
||||
| `process-analysis` | app-код — `routes/`, `app/Jobs`, `audit_*` | реконструкция бизнес-процесса из кода |
|
||||
| discovery-interview **FEATURE** | голова заказчика | интервью человека |
|
||||
| discovery-interview **SYSTEM** | мета-слой — карта, CLAUDE.md, MEMORY, Открытые_вопросы, Tooling, git log | интервью + синтез |
|
||||
|
||||
Правило разведения: если ответ добывается **чтением кода** — это `process-analysis`.
|
||||
Если ответ лежит в голове заказчика или в управляющих документах — это
|
||||
discovery-interview.
|
||||
|
||||
## Режим FEATURE
|
||||
|
||||
### Триггер
|
||||
|
||||
Заказчик описывает проблему, боль, раздражение или цель — но НЕ готовое решение.
|
||||
Признаки: «менеджеры жалуются…», «X теряется», «неудобно делать Y», «хочу, чтобы…»,
|
||||
«было бы хорошо, если…».
|
||||
|
||||
### SKIP
|
||||
|
||||
Не запускай FEATURE, если запрос — чёткий директив на реализацию: «интегрируй X»,
|
||||
«закрой находку Y», «поправь Z», «добавь endpoint». Проблема уже понята заказчиком,
|
||||
discovery только затормозит. Работай напрямую — или через `brainstorming`, если
|
||||
дизайн решения нетривиален.
|
||||
|
||||
Не запускай FEATURE и если запрос — **диагностика просадки измеримой метрики или
|
||||
конверсии** («почему падает конверсия B2», «где теряем в воронке», «почему лиды не
|
||||
доходят до оплаты»). Ответ там добывается анализом кода и audit-данных — это скил
|
||||
`process-analysis`. FEATURE — про UX-боль и желаемые возможности, не про диагностику
|
||||
чисел.
|
||||
|
||||
### Процесс
|
||||
|
||||
1. **Один вопрос за раз.** Не вываливай список — это интервью, не анкета. Ответ на
|
||||
первый вопрос определяет второй.
|
||||
2. **Спрашивай про прошлое поведение, не про гипотетику.** «Расскажи, как ты делал
|
||||
это в последний раз» сильнее, чем «как бы ты хотел». Люди плохо предсказывают
|
||||
своё поведение и точно помнят прошлое.
|
||||
3. **Копай до корня — «5 почему».** Первая названная проблема обычно симптом.
|
||||
4. **Не задавай наводящих вопросов.** «Тебе мешает отсутствие фильтра?» подсказывает
|
||||
ответ. Спроси открыто: «что именно замедляет тебя на этом экране?».
|
||||
5. **Поняв проблему — собери discovery-brief и остановись.** Не проектируй решение —
|
||||
это работа `brainstorming`.
|
||||
|
||||
Банк вопросов по шагам JTBD — `references/jtbd-questions.md`.
|
||||
|
||||
### Артефакт — discovery-brief
|
||||
|
||||
Проблема · JTBD (какую работу заказчик «нанимает» решение сделать) · Текущий обходной
|
||||
путь · Цена боли (время / деньги / частота) · Сигнал успеха (как поймём, что закрыто)
|
||||
· Ограничения. Шаблон — `docs/discovery/templates/discovery-brief.md`.
|
||||
|
||||
### Хэндофф
|
||||
|
||||
discovery-brief — это вход для `brainstorming`. Передай brief как готовую проблемную
|
||||
секцию: `brainstorming` берёт её и переходит к решению — он **не перезадаёт** уже
|
||||
выясненные вопросы. discovery-interview отвечает за «что за проблема», brainstorming —
|
||||
за «что построим». Отдельным файлом FEATURE-brief не сохраняется — он вливается в
|
||||
спеку brainstorming.
|
||||
|
||||
## Режим SYSTEM
|
||||
|
||||
### Триггер
|
||||
|
||||
Заказчик просит сориентировать его по состоянию проекта: «сориентируй», «где мы
|
||||
сейчас», «что у нас по X», «что в тулчейне / на карте», «catch-up».
|
||||
|
||||
### SKIP
|
||||
|
||||
Не запускай SYSTEM, если вопрос про устройство **бизнес-процесса** («как устроен
|
||||
процесс сделок», «process discovery», «где узкое место в воронке») — это скил
|
||||
`process-analysis`, он читает код. SYSTEM отвечает на «где мы в проекте», не «как
|
||||
работает процесс X».
|
||||
|
||||
### Процесс
|
||||
|
||||
1. **Короткое уточнение scope** — что именно ориентировать? Весь проект, конкретный
|
||||
раздел, тулчейн, открытые вопросы? Без scope ответ будет рыхлым.
|
||||
2. **Синтез по мета-слою:** карта `docs/automation-graph.html`, `CLAUDE.md`, MEMORY,
|
||||
`docs/Открытые_вопросы_*.md`, `docs/Tooling_*.md`, `git log`.
|
||||
3. **Запрет:** не читай `app/`-код для реконструкции процессов — это исключительный
|
||||
метод `process-analysis`. SYSTEM работает только с мета-слоем.
|
||||
4. **Выдай синтез**, а не пересказ документа целиком — ответ на запрос ориентации с
|
||||
пинами на источники.
|
||||
|
||||
### Артефакт — system-snapshot
|
||||
|
||||
Если ориентация существенная — сохрани `docs/discovery/YYYY-MM-DD-<тема>.md` по
|
||||
шаблону `docs/discovery/templates/system-snapshot.md`. Мелкий устный ответ файла не
|
||||
требует.
|
||||
|
||||
## JTBD-дисциплина (общая для обоих режимов)
|
||||
|
||||
- **Один вопрос за раз** — интервью, не анкета.
|
||||
- **Прошлое, не гипотетика** — «когда это случилось в последний раз?».
|
||||
- **«5 почему»** — корень, не симптом.
|
||||
- **Не наводи** — открытые вопросы, без подсказанного ответа.
|
||||
- **Слушай, не защищай** — если заказчик критикует существующее, не оправдывай его,
|
||||
копай дальше.
|
||||
|
||||
## Границы
|
||||
|
||||
- **`brainstorming`** — проектирование решения. discovery-interview вскрывает проблему
|
||||
и передаёт brief; brainstorming проектирует. Не дублируй его вопросы.
|
||||
- **`process-analysis`** (раздел C10) — анализ as-is бизнес-процесса из кода и
|
||||
диагностика метрик/конверсии. Если ответ требует чтения `routes/` / `app/Jobs` /
|
||||
`audit_*` или расчёта метрик процесса — это `process-analysis`, не этот скил.
|
||||
- **`audit-portal`** — качественный вердикт о здоровье портала. SYSTEM даёт
|
||||
ориентацию («где мы»), не вердикт («здорово ли»).
|
||||
- **Интервью конечных пользователей Лидерры** — вне этого скила (defer post-Б-1; для
|
||||
методологии user research — `design:user-research`).
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"skill_name": "discovery-interview",
|
||||
"note": "Триггер-eval: should_trigger=true → должен вызваться discovery-interview; false → должен сработать другой инструмент (expected_skill). Особое внимание — near-miss к process-analysis (C10).",
|
||||
"evals": [
|
||||
{ "id": 1, "should_trigger": true, "expected_skill": "discovery-interview/FEATURE", "prompt": "менеджеры жалуются что не видят, какие сделки сегодня надо обзвонить — каждое утро роются в фильтрах вручную" },
|
||||
{ "id": 2, "should_trigger": false, "expected_skill": "process-analysis", "prompt": "у меня ощущение что лиды из B2 проседают по конверсии, но не пойму почему — хочу разобраться" },
|
||||
{ "id": 3, "should_trigger": true, "expected_skill": "discovery-interview/FEATURE", "prompt": "хочу чтобы поставщики сами видели свой баланс, а то постоянно пишут в поддержку спрашивают" },
|
||||
{ "id": 4, "should_trigger": true, "expected_skill": "discovery-interview/FEATURE", "prompt": "проведи discovery interview по идее напоминаний — я пока сам не уверен что именно нужно" },
|
||||
{ "id": 5, "should_trigger": true, "expected_skill": "discovery-interview/FEATURE", "prompt": "не нравится как сейчас сделана выгрузка отчётов, неудобно, давай покопаем что не так" },
|
||||
{ "id": 6, "should_trigger": true, "expected_skill": "discovery-interview/FEATURE", "prompt": "клиенты часто отваливаются на этапе оплаты, надо понять что там за проблема" },
|
||||
{ "id": 7, "should_trigger": true, "expected_skill": "discovery-interview/SYSTEM", "prompt": "сориентируй меня — где мы сейчас по проекту, что закрыто что нет" },
|
||||
{ "id": 8, "should_trigger": true, "expected_skill": "discovery-interview/SYSTEM", "prompt": "что у нас вообще в тулчейне по безопасности, я запутался" },
|
||||
{ "id": 9, "should_trigger": true, "expected_skill": "discovery-interview/SYSTEM", "prompt": "вернулся после недели отсутствия, сделай catch-up что произошло по проекту" },
|
||||
{ "id": 10, "should_trigger": true, "expected_skill": "discovery-interview/SYSTEM", "prompt": "что там на карте в разделе биллинга, какие узлы" },
|
||||
{ "id": 11, "should_trigger": false, "expected_skill": "process-analysis", "prompt": "как устроен процесс обработки сделки от создания до закрытия — пройди по коду" },
|
||||
{ "id": 12, "should_trigger": false, "expected_skill": "process-analysis", "prompt": "где узкое место в воронке лидов, какой шаг тормозит" },
|
||||
{ "id": 13, "should_trigger": false, "expected_skill": "process-analysis", "prompt": "сделай process discovery по джобам импорта лидов" },
|
||||
{ "id": 14, "should_trigger": false, "expected_skill": "process-analysis", "prompt": "посчитай метрики процесса: cycle time по статусам сделок" },
|
||||
{ "id": 15, "should_trigger": false, "expected_skill": "directive (no skill)", "prompt": "интегрируй openapi-mcp-server в .mcp.json" },
|
||||
{ "id": 16, "should_trigger": false, "expected_skill": "directive (no skill)", "prompt": "закрой находку аудита G7 по AdminBillingController" },
|
||||
{ "id": 17, "should_trigger": false, "expected_skill": "systematic-debugging", "prompt": "поправь падающий тест RlsSmokeTest, он валится на teardown" },
|
||||
{ "id": 18, "should_trigger": false, "expected_skill": "directive (no skill)", "prompt": "добавь endpoint POST /api/deals/{id}/archive" },
|
||||
{ "id": 19, "should_trigger": false, "expected_skill": "write-spec / brainstorming", "prompt": "напиши спеку для фичи мультивалютного биллинга" },
|
||||
{ "id": 20, "should_trigger": false, "expected_skill": "audit-portal", "prompt": "проведи полный аудит портала перед релизом" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
# Банк вопросов JTBD — режим FEATURE
|
||||
|
||||
Вопросы для discovery-интервью. Задавать **по одному**, адаптируя формулировку под
|
||||
контекст. Все вопросы — про прошлое поведение, без подсказанного ответа.
|
||||
|
||||
## 1. Вскрыть проблему
|
||||
|
||||
- Расскажи, что произошло в последний раз, когда [ситуация]?
|
||||
- Что именно тебя в этом раздражало или замедляло?
|
||||
- Как часто это случается?
|
||||
|
||||
## 2. Текущий обходной путь
|
||||
|
||||
- Как ты решаешь это сейчас?
|
||||
- Что делаешь, когда [проблема] происходит?
|
||||
- Кто ещё это делает и как?
|
||||
|
||||
## 3. Цена боли
|
||||
|
||||
- Сколько времени это съедает за неделю?
|
||||
- Что случается, если не сделать это вовремя?
|
||||
- Были случаи, когда из-за этого что-то сорвалось?
|
||||
|
||||
## 4. JTBD — какую работу «нанимают» решение сделать
|
||||
|
||||
- Если бы это работало идеально — что бы ты перестал делать руками?
|
||||
- Какого результата ты на самом деле добиваешься?
|
||||
|
||||
## 5. Сигнал успеха
|
||||
|
||||
- Как ты поймёшь, что проблема закрыта?
|
||||
- Что должно стать видимо иначе?
|
||||
|
||||
## 6. Ограничения
|
||||
|
||||
- Что нельзя ломать или менять?
|
||||
- Есть ли срок?
|
||||
|
||||
## Антипаттерны
|
||||
|
||||
- **Наводящий вопрос** («тебе мешает отсутствие X?») — подсказывает ответ; заказчик
|
||||
согласится из вежливости.
|
||||
- **Гипотетика** («как бы ты хотел?») — люди плохо предсказывают своё поведение.
|
||||
- **Список вопросов разом** — это анкета, не интервью; теряется ветвление по ответам.
|
||||
- **Принять первый ответ за корень** — копай «5 почему» до настоящей причины.
|
||||
@@ -0,0 +1,62 @@
|
||||
---
|
||||
name: laravel-backend-patterns
|
||||
description: Backend-конвенции Лидерры (Laravel 13) — как писать controller→service→job, RLS-aware Eloquent, деньги через bcmath/LedgerService, идемпотентные джобы, partition-aware запросы. Используй при «как писать backend в Лидерре», «паттерн контроллера/сервиса/джоба», scaffolding новой backend-фичи. НЕ для generic-паттернов (architecture-patterns #38), аудита денег (billing-audit #62), РСБУ/налогов (ru-tax-accounting), security-аудита (D3).
|
||||
---
|
||||
|
||||
# Laravel Backend Patterns — конвенции backend-кода Лидерры
|
||||
|
||||
Проектный скил, который описывает **как здесь пишут backend**, а не как рекомендует generic-Laravel.
|
||||
При scaffolding новой фичи или ревью кода — сверяться с пятью конвенциями ниже.
|
||||
Детальные примеры с образцами кода и антипаттернами — в `references/conventions.md`.
|
||||
|
||||
## 1. Слоистость: Controller → FormRequest → Service → Job
|
||||
|
||||
Контроллер тонкий: принимает FormRequest, делегирует Service, возвращает JSON-ответ.
|
||||
Бизнес-логика — в Service; асинхронная работа — в Job.
|
||||
Слои зафиксированы в `app/deptrac.yaml` (13 слоёв, pre-commit gate job 10).
|
||||
|
||||
Подробнее: `references/conventions.md` §1.
|
||||
|
||||
## 2. RLS-aware Eloquent и middleware `tenant`
|
||||
|
||||
Middleware `SetTenantContext` оборачивает HTTP-запрос в транзакцию и выполняет
|
||||
`SET LOCAL app.current_tenant_id = X`, обеспечивая RLS-изоляцию между tenant'ами.
|
||||
**КРИТИЧНО**: очередные джобы выполняются под ролью `crm_supplier_worker` (BYPASSRLS),
|
||||
поэтому RLS не фильтрует. Каждый запрос в джобе **обязан** содержать явный
|
||||
`where('tenant_id', $tenantId)` или устанавливать `SET LOCAL` вручную внутри транзакции.
|
||||
|
||||
Подробнее: `references/conventions.md` §2.
|
||||
|
||||
## 3. Деньги — только через bcmath и LedgerService
|
||||
|
||||
Все денежные операции — `bcadd` / `bcsub` / `bcmul` / `bcdiv` / `bccomp` со строковыми операндами
|
||||
и фиксированным `scale`. Никаких операторов `+` / `-` / `*` / `/` над деньгами, никакого `float`.
|
||||
Точка входа для биллингового списания — `LedgerService::chargeForDelivery()`.
|
||||
Аудит денежных инвариантов кода — скил `billing-audit` (#62); здесь — только конвенция написания.
|
||||
|
||||
Подробнее: `references/conventions.md` §3.
|
||||
|
||||
## 4. Идемпотентные джобы через advisory lock
|
||||
|
||||
Повторный запуск джоба не должен дублировать результат.
|
||||
Паттерн: `pg_advisory_xact_lock(composite_bigint)` внутри транзакции — сериализует
|
||||
конкурентные обработки одного (tenant_id, source_crm_id). Дополнительно: `lockForUpdate`
|
||||
на строку Tenant защищает баланс от TOCTOU при конкурентных списаниях.
|
||||
|
||||
Подробнее: `references/conventions.md` §4.
|
||||
|
||||
## 5. Partition-aware запросы для `deals` и `supplier_lead_costs`
|
||||
|
||||
Таблицы `deals` и `supplier_lead_costs` секционированы по `RANGE (received_at)`.
|
||||
Запросы к этим таблицам должны включать условие по `received_at` (или `created_at`
|
||||
для `supplier_lead_costs`) — это включает pruning и предотвращает full-scan всех партиций.
|
||||
|
||||
Подробнее: `references/conventions.md` §5.
|
||||
|
||||
## Связано
|
||||
|
||||
- `billing-audit` #62 — аудит денежной корректности (I1–I5 инварианты).
|
||||
- `architecture-patterns` #38 — общие паттерны архитектуры (не Лидерра-специфика).
|
||||
- Boost #10 — Eloquent introspection, документация Laravel 13.
|
||||
- Larastan #12 — статанализ PHP (ловит float-арифметику на деньгах).
|
||||
- ADR-005 — deptrac architecture-fitness gate.
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"skill": "laravel-backend-patterns",
|
||||
"cases": [
|
||||
{"prompt": "как написать контроллер для новой backend-фичи в Лидерре", "should_trigger": true},
|
||||
{"prompt": "как правильно списать деньги в джобе под crm_supplier_worker", "should_trigger": true},
|
||||
{"prompt": "проверь, не теряются ли копейки в списании", "should_trigger": false, "expected": "billing-audit"},
|
||||
{"prompt": "опиши Clean Architecture в общем", "should_trigger": false, "expected": "architecture-patterns"},
|
||||
{"prompt": "учёт выручки по РСБУ", "should_trigger": false, "expected": "ru-tax-accounting"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
# Backend-конвенции Лидерры — детальный справочник
|
||||
|
||||
Образцы ниже — реальный код из `app/` (Laravel 13, PHP 8.3).
|
||||
Указаны конкретные `file:line` на момент 20.05.2026.
|
||||
|
||||
---
|
||||
|
||||
## §1. Слоистость: Controller → FormRequest → Service → Job
|
||||
|
||||
### Правило
|
||||
|
||||
Контроллер принимает FormRequest (валидация), делегирует Service (бизнес-логика),
|
||||
при необходимости Service dispatch'ит Job (асинхрон). Контроллер не содержит бизнес-логики.
|
||||
Слои задокументированы в `app/deptrac.yaml` — 13 слоёв:
|
||||
Controller, Request, Resource, Middleware, Service, Job, Console, Repository,
|
||||
Model, Mail, Rule, Exception, Provider.
|
||||
Допустимые направления зависимостей — только вниз по иерархии (deptrac gate, lefthook job 10).
|
||||
|
||||
### Образец из кода
|
||||
|
||||
`app/app/Http/Controllers/Api/ProjectController.php:87–90` — контроллер тонкий:
|
||||
|
||||
```php
|
||||
/** POST /api/projects */
|
||||
public function store(StoreProjectRequest $request): JsonResponse
|
||||
{
|
||||
$project = $this->projects->create($request->user()->tenant, $request->validated());
|
||||
|
||||
return response()->json(['data' => new ProjectResource($project)], 201);
|
||||
}
|
||||
```
|
||||
|
||||
`app/app/Http/Requests/StoreProjectRequest.php:18–44` — вся валидация в FormRequest:
|
||||
|
||||
```php
|
||||
public function rules(): array
|
||||
{
|
||||
$base = [
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'signal_type' => ['required', Rule::in(['site', 'call', 'sms'])],
|
||||
'daily_limit_target' => ['required', 'integer', 'min:1', 'max:10000'],
|
||||
'regions' => ['present', 'array'],
|
||||
'regions.*' => ['integer', 'between:1,89'],
|
||||
'delivery_days_mask' => ['required', 'integer', 'min:1', 'max:127'],
|
||||
];
|
||||
// ... conditional rules by signal_type
|
||||
return $base;
|
||||
}
|
||||
```
|
||||
|
||||
`app/app/Services/Billing/LedgerService.php` — бизнес-логика в Service.
|
||||
`app/app/Jobs/ProcessWebhookJob.php` — асинхрон в Job.
|
||||
|
||||
### Антипаттерн
|
||||
|
||||
```php
|
||||
// ПЛОХО: бизнес-логика в контроллере
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$tier = PricingTier::where('min_leads', '<=', $count)->orderBy('min_leads', 'desc')->first();
|
||||
$price = $tier->price_per_lead_kopecks * $count; // float-арифметика + логика тира прямо здесь
|
||||
Deal::create([...]);
|
||||
return response()->json(['ok' => true]);
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## §2. RLS-aware Eloquent и middleware `tenant`
|
||||
|
||||
### Правило
|
||||
|
||||
Middleware `SetTenantContext` (`app/app/Http/Middleware/SetTenantContext.php`) оборачивает
|
||||
каждый HTTP-запрос в транзакцию и выполняет `SET LOCAL app.current_tenant_id = X`,
|
||||
после чего RLS-политики PostgreSQL автоматически фильтруют строки по tenant.
|
||||
|
||||
**КРИТИЧНО для джобов**: очередные джобы Laravel выполняются в отдельном процессе вне
|
||||
HTTP-стека. Роль `crm_supplier_worker` (connection `pgsql_supplier`) имеет атрибут
|
||||
BYPASSRLS — RLS-политики для неё **не применяются**. Любой запрос в таком джобе без
|
||||
явного `where('tenant_id', $tenantId)` вернёт строки всех tenant'ов.
|
||||
|
||||
Правило: в каждом джобе либо устанавливай `SET LOCAL` внутри транзакции (паттерн
|
||||
`ProcessWebhookJob`/`ImportLeadsJob`), либо добавляй явный `where('tenant_id', ...)`.
|
||||
|
||||
### Образец из кода
|
||||
|
||||
`app/app/Http/Middleware/SetTenantContext.php:36–43` — HTTP-путь:
|
||||
|
||||
```php
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
DB::statement('SET LOCAL app.current_tenant_id = ' . $tenantId);
|
||||
$response = $next($request);
|
||||
DB::commit();
|
||||
return $response;
|
||||
} catch (\Throwable $e) {
|
||||
DB::rollBack();
|
||||
throw $e;
|
||||
}
|
||||
```
|
||||
|
||||
`app/app/Jobs/ImportLeadsJob.php:92–96` — джоб устанавливает `SET LOCAL` вручную:
|
||||
|
||||
```php
|
||||
return DB::transaction(function (): ?ImportLog {
|
||||
DB::statement('SET LOCAL app.current_tenant_id = ' . $this->tenantId);
|
||||
return ImportLog::query()->find($this->importLogId);
|
||||
});
|
||||
```
|
||||
|
||||
`app/app/Jobs/ProcessWebhookJob.php:80–86` — аналогичный паттерн в webhook-джобе:
|
||||
|
||||
```php
|
||||
DB::transaction(function () use ($duplicateDetector): void {
|
||||
DB::statement('SET LOCAL app.current_tenant_id = ' . $this->tenantId);
|
||||
$tenant = Tenant::query()
|
||||
->whereKey($this->tenantId)
|
||||
->lockForUpdate()
|
||||
->first();
|
||||
```
|
||||
|
||||
### Антипаттерн
|
||||
|
||||
```php
|
||||
// ПЛОХО: джоб под crm_supplier_worker без SET LOCAL и без where tenant_id
|
||||
// → вернёт все строки всех tenant'ов (BYPASSRLS не фильтрует)
|
||||
public function handle(): void
|
||||
{
|
||||
$logs = ImportLog::query()->where('status', 'pending')->get(); // ВСЕ tenant'ы!
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## §3. Деньги — только через bcmath и LedgerService
|
||||
|
||||
### Правило
|
||||
|
||||
Все арифметические операции с деньгами (рубли, копейки) — исключительно через
|
||||
функции `bcmath` с явным `scale`. Операнды передаются строками.
|
||||
Никаких PHP `float`, никакого `+` / `-` / `*` / `/` над денежными значениями.
|
||||
|
||||
Точка входа для списания за лид — `LedgerService::chargeForDelivery()`.
|
||||
Этот метод реализует dual-balance flow (prepaid-лиды → `balance_leads`, рубли → `balance_rub`).
|
||||
Вызывается **внутри открытой транзакции** с `lockForUpdate(Tenant)` — см. §4.
|
||||
|
||||
Аудит денежных инвариантов (I1–I5) — скил `billing-audit` (#62). Здесь — конвенция написания.
|
||||
|
||||
### Образец из кода
|
||||
|
||||
`app/app/Services/Billing/LedgerService.php:64–65` — конвертация копеек в рубли:
|
||||
|
||||
```php
|
||||
$amountRub = bcdiv((string) $priceKopecks, '100', 2);
|
||||
$newBalanceRub = bcsub((string) $lockedTenant->balance_rub, $amountRub, 2);
|
||||
```
|
||||
|
||||
`app/app/Services/Billing/LedgerService.php:124–125` — сравнение балансов:
|
||||
|
||||
```php
|
||||
$balanceKopecks = bcmul((string) $tenant->balance_rub, '100', 0);
|
||||
if (bccomp($balanceKopecks, (string) $priceKopecks, 0) >= 0) {
|
||||
return 'rub';
|
||||
}
|
||||
```
|
||||
|
||||
### Антипаттерн
|
||||
|
||||
```php
|
||||
// ПЛОХО: float-арифметика теряет копейки
|
||||
$price = $tier->price_per_lead_kopecks / 100; // float
|
||||
$newBalance = $tenant->balance_rub - $price; // потеря точности при накоплении
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## §4. Идемпотентные джобы через advisory lock
|
||||
|
||||
### Правило
|
||||
|
||||
Повторный запуск джоба (ретрай, краш, дубль cron) не должен создавать дублирующие
|
||||
записи. Паттерн: `pg_advisory_xact_lock(bigint)` внутри транзакции сериализует все
|
||||
конкурентные обработки одного (tenant_id, source_crm_id).
|
||||
|
||||
Дополнительно для мутаций баланса: `lockForUpdate` на строку Tenant — защита от
|
||||
TOCTOU (между чтением баланса и его обновлением другой воркер не должен изменить значение).
|
||||
|
||||
### Образец из кода
|
||||
|
||||
`app/app/Jobs/ProcessWebhookJob.php:293–296` — advisory lock перед upsert:
|
||||
|
||||
```php
|
||||
// pg_advisory_xact_lock(bigint): верхние 32 бита = tenant_id, нижние 32 = source_crm_id
|
||||
$lockKey = (($tenant->id & 0xFFFFFFFF) << 32) | ($sourceCrmId & 0xFFFFFFFF);
|
||||
DB::statement('SELECT pg_advisory_xact_lock(?)', [$lockKey]);
|
||||
```
|
||||
|
||||
`app/app/Services/Import/HistoricalImportService.php:145–147` — тот же паттерн в сервисе:
|
||||
|
||||
```php
|
||||
// advisory lock (tenant_id, source_crm_id) — сериализует upsert (§6.5)
|
||||
$lockKey = (($tenantId & 0xFFFFFFFF) << 32) | ($row->sourceCrmId & 0xFFFFFFFF);
|
||||
DB::statement('SELECT pg_advisory_xact_lock(?)', [$lockKey]);
|
||||
```
|
||||
|
||||
`app/app/Jobs/RouteSupplierLeadJob.php:210–213` — lockForUpdate на Tenant перед списанием:
|
||||
|
||||
```php
|
||||
$tenant = Tenant::query()
|
||||
->whereKey($project->tenant_id)
|
||||
->lockForUpdate()
|
||||
->firstOrFail();
|
||||
```
|
||||
|
||||
Для overlap-защиты долгоживущих джобов (cron) — `Cache::lock` (Redis):
|
||||
`app/app/Jobs/Supplier/CsvReconcileJob.php:69–74`:
|
||||
|
||||
```php
|
||||
$lock = $lockStore->lock(self::LOCK_NAME, self::LOCK_TTL_SECONDS);
|
||||
if (! $lock->get()) {
|
||||
Log::info('csv_reconcile.skipped_overlap');
|
||||
return;
|
||||
}
|
||||
```
|
||||
|
||||
### Антипаттерн
|
||||
|
||||
```php
|
||||
// ПЛОХО: нет lock — два конкурентных воркера создают два deal для одного vid
|
||||
$existing = Deal::where('source_crm_id', $vid)->where('tenant_id', $tenantId)->first();
|
||||
if (!$existing) {
|
||||
Deal::create([...]); // race condition: оба воркера видят null и оба создают
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## §5. Partition-aware запросы для `deals` и `supplier_lead_costs`
|
||||
|
||||
### Правило
|
||||
|
||||
Таблицы `deals` и `supplier_lead_costs` секционированы по `PARTITION BY RANGE (received_at)`.
|
||||
Запросы должны содержать условие по `received_at` (ключ партиционирования) — это позволяет
|
||||
PostgreSQL выполнять partition pruning и не сканировать все партиции.
|
||||
Запрос без `WHERE received_at ...` делает full-scan всех партиций.
|
||||
|
||||
### Образец из кода
|
||||
|
||||
`db/schema.sql:1658` — партиционирование `deals`:
|
||||
|
||||
```sql
|
||||
) PARTITION BY RANGE (received_at);
|
||||
```
|
||||
|
||||
`db/schema.sql:2361` — партиционирование `supplier_lead_costs`:
|
||||
|
||||
```sql
|
||||
) PARTITION BY RANGE (received_at);
|
||||
```
|
||||
|
||||
`app/app/Services/DuplicateDetector.php:49` — запрос к `deals` с ключом партиции:
|
||||
|
||||
```php
|
||||
->where('received_at', '>=', $windowStart)
|
||||
```
|
||||
|
||||
`app/app/Jobs/Supplier/CsvReconcileJob.php:113` — запрос к `supplier_leads` с ключом:
|
||||
|
||||
```php
|
||||
->where('received_at', '>=', $windowStart)
|
||||
```
|
||||
|
||||
### Антипаттерн
|
||||
|
||||
```php
|
||||
// ПЛОХО: запрос к deals без received_at — full-scan всех партиций
|
||||
$deals = Deal::where('tenant_id', $tenantId)
|
||||
->where('phone', $phone)
|
||||
->get(); // сканирует deals_2026_05, deals_2026_06, ... все партиции
|
||||
```
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
name: process-analysis
|
||||
description: Анализ и оптимизация существующего бизнес-процесса — process discovery (реконструкция as-is процесса из кода Laravel и audit-логов), поиск узких мест, трассировка требование→процесс, метрики и KPI процесса. Триггеры — «проанализируй процесс», «где узкое место», «process discovery», «как устроен процесс X», «метрики процесса», «оптимизируй процесс». Раздел C10 карты «Бизнес-процессы (общее)».
|
||||
---
|
||||
|
||||
# Process Analysis
|
||||
|
||||
Разбирает **существующий** бизнес-процесс: восстанавливает фактическую модель,
|
||||
находит узкие места, считает метрики. Парный скил к `process-modeling` — тот
|
||||
проектирует to-be, этот вскрывает as-is.
|
||||
|
||||
## Четыре режима
|
||||
|
||||
### 1. Process discovery — реконструкция as-is
|
||||
|
||||
Восстановить фактический процесс из артефактов кода (карта источников —
|
||||
`references/discovery.md`): маршруты + контроллеры (точки входа), джобы/события
|
||||
(асинхронные шаги), enum статусов + переходы (state-машина), audit-таблицы
|
||||
(фактические следы), cron/scheduler (периодические шаги). Итог — модель,
|
||||
которую можно передать `process-modeling` для отрисовки.
|
||||
|
||||
### 2. Bottleneck — поиск узких мест
|
||||
|
||||
Паттерны: ручной шаг между авто-шагами; шаг с ожиданием внешней системы; точка
|
||||
сериализации (advisory-lock, `lockForUpdate`); N+1 внутри шага; ретраи/таймауты;
|
||||
шаг с наибольшей долей исключений.
|
||||
Граница: это **процессные** узкие места. Runtime/код-производительность —
|
||||
`perf-analyzer` / скил `analysis:bottleneck-detect` (PA1).
|
||||
|
||||
### 3. Трассировка требование→процесс
|
||||
|
||||
Связать пункт ТЗ / `Открытые_вопросы` → шаги процесса → код (file:line) →
|
||||
тесты. Выявить шаги без требования (скрытая логика) и требования без
|
||||
реализации.
|
||||
|
||||
### 4. Метрики процесса
|
||||
|
||||
Определить KPI: throughput, cycle time, конверсия между статусами, доля
|
||||
исключений, объём ручного труда. Числа берутся из БД через `Boost`, не
|
||||
выдумываются.
|
||||
Граница: продуктовые метрики — плагин `product-management` (`/metrics-review`).
|
||||
|
||||
## Рабочий процесс
|
||||
|
||||
1. Определить режим (1-4) по запросу.
|
||||
2. Собрать факты из кода / БД / логов — никаких допущений без пинов (file:line).
|
||||
3. Выдать находки: модель / список узких мест / матрицу трассировки / таблицу
|
||||
метрик.
|
||||
4. Рекомендации направить в `process-modeling` (to-be) или в задачи. Этот скил
|
||||
код не правит.
|
||||
|
||||
## Границы
|
||||
|
||||
- **Проектирование to-be модели** — скил `process-modeling`.
|
||||
- **Runtime / код-производительность** — `perf-analyzer`,
|
||||
`analysis:bottleneck-detect` (PA1).
|
||||
- **Продуктовые метрики** — плагин `product-management`.
|
||||
- **Документ / change-request процесса** — плагин `operations`.
|
||||
- **Интервью заказчика про будущую фичу / ориентация по проекту** — скил
|
||||
`discovery-interview`. Тот вскрывает проблему до решения через интервью человека
|
||||
(режим FEATURE) и синтезирует мета-слой проекта (режим SYSTEM); этот скил — про
|
||||
вскрытие as-is процесса из app-кода. «process discovery», «как устроен процесс X»,
|
||||
«где узкое место» — сюда; «проведи discovery interview», «сориентируй по проекту» —
|
||||
в `discovery-interview`.
|
||||
- **Генерик-методология оптимизации процесса** — скил `process-optimization`
|
||||
плагина `operations`. Этот скил — про code-grounded discovery конкретного
|
||||
процесса Лидерры (вскрытие as-is), не про общую методологию и не про
|
||||
проектирование to-be.
|
||||
@@ -0,0 +1,32 @@
|
||||
# Process discovery — карта источников as-is процесса в Лидерре
|
||||
|
||||
Где в коде Лидерры лежат факты о фактическом бизнес-процессе.
|
||||
|
||||
## Источники
|
||||
|
||||
| Артефакт процесса | Где искать |
|
||||
|---|---|
|
||||
| Точки входа процесса | `app/routes/*.php` + `app/app/Http/Controllers/**` |
|
||||
| Синхронные шаги | методы контроллеров + `app/app/Services/**` |
|
||||
| Асинхронные шаги | `app/app/Jobs/**`, `app/app/Events/**` + listeners |
|
||||
| State-машина | enum/константы статусов + `db/schema.sql` (воронка — 14 статусов) |
|
||||
| Фактические следы выполнения | `audit_*` таблицы, `audit_chain_hash` (событийный лог) |
|
||||
| Периодические шаги | `app/app/Console/**` + scheduler (`partitions:create-months` и пр.) |
|
||||
| Бизнес-правила в шагах | `calc_lead_score` (SQL), `PricingTierResolver`, `LedgerService` |
|
||||
|
||||
## Метод
|
||||
|
||||
1. От **точки входа** (route → controller) пройти по вызовам до терминального
|
||||
состояния.
|
||||
2. Каждый `dispatch()` / событие — асинхронная ветка; проследить listener/job.
|
||||
3. Переход статуса = ребро state-машины; собрать все переходы в автомат.
|
||||
4. Свериться с **audit-логом**: фактический порядок событий в `audit_*` может
|
||||
расходиться с «проектным» — расхождение само по себе находка.
|
||||
5. Зафиксировать каждый шаг пином `file:line`; без пина — это допущение, не факт.
|
||||
|
||||
## Антипаттерны при discovery
|
||||
|
||||
- Принять «happy path» за весь процесс — исключения (catch, failed jobs,
|
||||
таймауты) тоже шаги.
|
||||
- Пропустить cron-шаги — они не видны из route-графа.
|
||||
- Доверять имени метода вместо его тела.
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
name: process-modeling
|
||||
description: Моделирование бизнес-процесса — BPMN 2.0 (пулы, дорожки, задачи, гейтвеи, события), карты процессов, customer-journey / value-stream, RACI-матрицы, state-машины. Триггеры — «смоделируй процесс», «нарисуй BPMN», «карта процесса», «swimlane / дорожки», «customer journey», «RACI», проектирование state-машины (воронка сделок, цепочка джобов). Раздел C10 карты «Бизнес-процессы (общее)».
|
||||
---
|
||||
|
||||
# Process Modeling
|
||||
|
||||
Превращает словесное описание бизнес-процесса в формальную модель. Скил даёт
|
||||
**нотацию и методологию** — рендер диаграмм делегируется скилу `mermaid`
|
||||
(process-modeling не рендерит сам — конфликт-граница OPS1/BPMN1: mermaid
|
||||
остаётся рендер-SoT).
|
||||
|
||||
## Когда какой артефакт
|
||||
|
||||
| Нужно | Артефакт |
|
||||
|---|---|
|
||||
| Кто-что-в-каком-порядке делает, с ветвлениями | BPMN 2.0 / swimlane |
|
||||
| Сквозной поток end-to-end крупными блоками | Карта процесса (flowchart) |
|
||||
| Опыт клиента/лида по этапам + точки боли | Customer-journey map |
|
||||
| Поток создания ценности + потери и ожидания | Value-stream map |
|
||||
| Распределение ответственности по шагам | RACI-матрица |
|
||||
| Конечный автомат (статусы + переходы) | State-диаграмма |
|
||||
|
||||
## Рабочий процесс
|
||||
|
||||
1. **Собрать процесс** — уточнить: триггер (что запускает), участники (роли),
|
||||
шаги по порядку, ветвления и условия, итог, исключения. Неясное — один
|
||||
вопрос за раз.
|
||||
2. **Выбрать артефакт** по таблице выше.
|
||||
3. **Построить модель** в нотации (BPMN — см. `references/bpmn.md`).
|
||||
4. **Отрендерить** — передать исходник скилу `mermaid`.
|
||||
5. **Свериться** — модель не должна противоречить ТЗ / `db/schema.sql` /
|
||||
`Открытые_вопросы`. Процесс вне ТЗ И не в реестре открытых вопросов —
|
||||
hard-стоп (Pravila §7): не моделировать молча, поднять вопрос.
|
||||
|
||||
## BPMN 2.0 — ядро
|
||||
|
||||
Полная нотация и маппинг на mermaid — `references/bpmn.md`. Кратко:
|
||||
|
||||
- **Pool** — организация/система; **Lane** — роль внутри pool.
|
||||
- **Task** — атомарное действие; **Sub-process** — свёрнутый под-поток.
|
||||
- **Gateway** — ветвление: exclusive (XOR — один путь), parallel (AND — все
|
||||
пути), inclusive (OR — один и более).
|
||||
- **Event** — start / intermediate / end; типы: timer, message, error.
|
||||
- **Sequence flow** — порядок внутри pool; **Message flow** — между pool'ами.
|
||||
|
||||
## Границы
|
||||
|
||||
- **Рендер диаграмм** — скил `mermaid` (C10 OPS1/BPMN1). Этот скил исходник не
|
||||
рисует — отдаёт его mermaid.
|
||||
- **DDD-границы доменных процессов** — скил `architecture-patterns` (bounded
|
||||
context = граница бизнес-процесса).
|
||||
- **Документ процесса, change-request, оптимизация** — плагин `operations`
|
||||
(скилы `process-doc`, `change-request`, `process-optimization`).
|
||||
- **Анализ as-is процесса** (discovery, узкие места) — скил `process-analysis`.
|
||||
- Этот скил — про проектирование **to-be модели**, не про вскрытие as-is.
|
||||
@@ -0,0 +1,56 @@
|
||||
# BPMN 2.0 — справочник нотации и рендер в mermaid
|
||||
|
||||
mermaid не имеет нативного BPMN-рендера. BPMN-модель выражается через mermaid
|
||||
`flowchart` (swimlane через `subgraph` = дорожки) или `stateDiagram-v2`.
|
||||
|
||||
## Элементы BPMN → mermaid
|
||||
|
||||
| BPMN | Смысл | mermaid-выражение |
|
||||
|---|---|---|
|
||||
| Pool / Lane | организация / роль | `subgraph Роль ... end` |
|
||||
| Task | действие | прямоугольник `id[Текст]` |
|
||||
| Sub-process | свёрнутый поток | `id[[Текст]]` |
|
||||
| Start event | старт | `id((Старт))` |
|
||||
| End event | конец | `id((Конец))` |
|
||||
| Exclusive gateway (XOR) | один путь | ромб `id{Условие?}` + подписи на рёбрах |
|
||||
| Parallel gateway (AND) | все пути | ромб `id{И}` с несколькими исходящими |
|
||||
| Sequence flow | порядок | `-->` |
|
||||
| Message flow | между pool | `-.->` |
|
||||
|
||||
## Шаблон swimlane
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph Менеджер
|
||||
A((Старт)) --> B[Принять лид]
|
||||
B --> C{Лид валиден?}
|
||||
end
|
||||
subgraph Система
|
||||
C -->|да| D[Создать сделку]
|
||||
C -->|нет| E((Отклонён))
|
||||
D --> F((Сделка создана))
|
||||
end
|
||||
```
|
||||
|
||||
## State-машина
|
||||
|
||||
Для конечных автоматов (воронка сделок — 14 статусов из `db/schema.sql`)
|
||||
использовать `stateDiagram-v2`:
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> new
|
||||
new --> in_progress
|
||||
in_progress --> won
|
||||
in_progress --> lost
|
||||
won --> [*]
|
||||
lost --> [*]
|
||||
```
|
||||
|
||||
Статус-слаги — из `db/schema.sql` (источник истины воронки), не выдумывать.
|
||||
|
||||
## Правила
|
||||
|
||||
- Один gateway — один вопрос; каждое исходящее ребро подписано условием.
|
||||
- Каждый путь оканчивается end-событием (нет «висящих» задач).
|
||||
- Исключения (timer/error) моделировать явно, не прятать в «happy path».
|
||||
@@ -0,0 +1,43 @@
|
||||
---
|
||||
name: ru-tax-accounting
|
||||
description: Контекст РСБУ и налогов РФ (НК РФ, НДС/УСН) применительно к SaaS-выручке Лидерры за лиды. Используй при «учёт выручки по РСБУ», «НДС или УСН», «налоговая база по выручке», «налогооблагаемое событие», «выгрузка для бухгалтера», «проводки РСБУ». НЕ для денежной корректности кода (billing-audit), US-GAAP-отчётности (finance plugin), договоров (D1 право), ПДн (D2), сверки с банком (finance reconciliation).
|
||||
---
|
||||
|
||||
# RU Tax & Accounting — РСБУ/НК РФ контекст для выручки Лидерры
|
||||
|
||||
Проектный скил раздела C7 карты «Финансы — бухгалтерия и налоги». Переводит
|
||||
billing-выручку (выход C6) в **российский учётно-налоговый контекст** (РСБУ + НК РФ).
|
||||
Закрывает gap, который US-GAAP-плагин `finance` (#61) не покрывает.
|
||||
|
||||
## Когда использовать
|
||||
|
||||
- Вопрос «как это учесть/обложить по РФ-правилам?» по выручке/пополнениям/возвратам.
|
||||
- Подготовка выгрузок/пояснений для бухгалтера из billing-данных.
|
||||
- Определение налогооблагаемого события и налоговой базы.
|
||||
|
||||
## Содержание (см. references/ru-tax-context.md)
|
||||
|
||||
1. **Налоговые режимы РФ** — НДС (ОСНО) vs УСН (доходы / доходы-расходы); что применимо к SaaS за лиды.
|
||||
2. **Налогооблагаемое событие** — пополнение баланса (аванс) vs списание за лид (реализация) vs возврат.
|
||||
3. **Маппинг billing→база** — `lead_charges`/`LedgerService` → выручка → налоговая база; роль `charge_source`.
|
||||
4. **РСБУ vs управленческий** — отличие от US-GAAP-отчётов плагина finance; первичка/документы.
|
||||
5. **Выгрузки для бухгалтера** — какие данные и в каком разрезе извлечь (Boost/Pest как инструменты выгрузки).
|
||||
|
||||
## Границы
|
||||
|
||||
- ≠ `billing-audit` #62 — тот про *корректность начисления в коде*; ru-tax про *учёт/налог результата*.
|
||||
- ≠ `finance` plugin #61 — тот US-GAAP-механика (проводки/отчёты/сверка); ru-tax — РФ-специфика РСБУ/НК.
|
||||
- ≠ D1 «Юриспруденция/договорная» — там договоры/право; ru-tax — налоги.
|
||||
- ≠ D2 «Защита ПДн (152-ФЗ)» — там персональные данные; ru-tax — налоги.
|
||||
|
||||
## Ограничение
|
||||
|
||||
Бухгалтерия компании ведётся вне dev-репо (1С/аутсорс). Скил даёт **контекст и выгрузки**,
|
||||
не заменяет бухгалтера и не является налоговой консультацией. Реальный платёжный
|
||||
провайдер — DEFERRED (Б-1).
|
||||
|
||||
## Связано
|
||||
|
||||
- Вход: выручка из C6 (`lead_charges`, `LedgerService`).
|
||||
- Reuse: data-scientist #49 (финмодели), Boost #10 / Pest #18 (выгрузка), finance plugin #61 (US-механика).
|
||||
- ADR-012 (граница finance-tooling C6/C7).
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"skill": "ru-tax-accounting",
|
||||
"positive": [
|
||||
"как учесть выручку за лиды по РСБУ",
|
||||
"НДС или УСН для SaaS-выручки",
|
||||
"переведи billing-выручку в налоговую базу",
|
||||
"какое налогооблагаемое событие при пополнении баланса",
|
||||
"выгрузка lead_charges для бухгалтера",
|
||||
"проводки по РСБУ за списания",
|
||||
"налоговый режим для подписочной выручки портала",
|
||||
"что с НДС при возврате на баланс tenant",
|
||||
"налоговая база УСН доходы по выручке за лиды"
|
||||
],
|
||||
"near_miss": [
|
||||
{"prompt": "проверь идемпотентность списания", "expect": "billing-audit #62"},
|
||||
{"prompt": "US-GAAP financial statement", "expect": "finance plugin #61 financial-statements"},
|
||||
{"prompt": "договор с поставщиком лидов", "expect": "D1 юриспруденция"},
|
||||
{"prompt": "обработка ПДн при выгрузке", "expect": "D2 ПДн 152-ФЗ"},
|
||||
{"prompt": "сверка ledger с банком", "expect": "finance plugin #61 reconciliation"}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
# РСБУ / НК РФ — контекст для выручки Лидерры за лиды
|
||||
|
||||
> Не налоговая консультация. Контекст для подготовки данных бухгалтеру.
|
||||
|
||||
## 1. Налоговые режимы РФ
|
||||
|
||||
- **ОСНО + НДС (НК РФ гл. 21)** — НДС 20% на реализацию услуг РФ. Электронные/рекламные
|
||||
услуги — проверить место реализации и применимые льготы.
|
||||
- **УСН (НК РФ гл. 26.2)** — «доходы» (6%) или «доходы минус расходы» (15%). Без НДС
|
||||
(кроме исключений). Типичный режим для раннего SaaS.
|
||||
- Применимый режим зависит от регистрации ООО (Б-1) — до закрытия Б-1 фиксируем как параметр.
|
||||
|
||||
## 2. Налогооблагаемое событие
|
||||
|
||||
- **Пополнение баланса** = аванс (предоплата). По НДС — момент определения базы может
|
||||
возникать на аванс; по УСН-доходы — доход по поступлению (кассовый метод).
|
||||
- **Списание за лид** = реализация услуги (закрытие аванса).
|
||||
- **Возврат на баланс / с баланса** = корректировка базы.
|
||||
- Различать по `lead_charges.charge_source` и операциям `LedgerService`.
|
||||
|
||||
## 3. Маппинг billing → налоговая база
|
||||
|
||||
| Billing-сущность | Учётный смысл |
|
||||
|---|---|
|
||||
| Пополнение (`BillingTopupService`) | Аванс / поступление |
|
||||
| Списание (`LedgerService`, `lead_charges`) | Реализация (выручка) |
|
||||
| `delivered_in_month` (`tenants`) | Объём для tier — не налог напрямую |
|
||||
| Возврат | Корректировка |
|
||||
|
||||
## 4. РСБУ vs управленческий / US-GAAP
|
||||
|
||||
- РСБУ — российский план счетов, первичные документы (акт/УПД), кассовый/начисление.
|
||||
- US-GAAP-скилы плагина `finance` (#61) — иная форма (income statement / balance sheet);
|
||||
применимы для *внутренней управленки*, не для РФ-отчётности.
|
||||
|
||||
## 5. Выгрузки для бухгалтера
|
||||
|
||||
- Реестр списаний за период: `lead_charges` (period, tenant, сумма, charge_source).
|
||||
- Реестр пополнений: операции `LedgerService` / `BillingTopupService`.
|
||||
- Инструменты выгрузки: Boost #10 (Eloquent/SQL), Pest #18 (фикстуры/проверки), `BillingSummaryProvider` (готовый отчёт-провайдер).
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
name: subagent-driven-development
|
||||
description: Project-local wrapper для superpowers:subagent-driven-development — добавляет обязательный git-safety verify-протокол per Pravila §15.1. Использовать вместо marketplace-варианта при работе с git-коммит-задачами в субагентах.
|
||||
---
|
||||
|
||||
# Subagent-Driven Development (project wrapper)
|
||||
|
||||
Этот скил — проектная обёртка над marketplace-скилом `superpowers:subagent-driven-development`. Дополняет его обязательным git-safety verify-протоколом per Pravila §15.1.
|
||||
|
||||
## Когда использовать
|
||||
|
||||
Когда нужно делегировать задачу субагенту через Task tool — особенно git-коммит-задачи (Sprint 6 прецедент: Haiku-субагенты угнали ветку параллельной сессии).
|
||||
|
||||
## Что делать
|
||||
|
||||
1. **Откройте marketplace-скил** `superpowers:subagent-driven-development` для общего workflow (fresh subagent per task + two-stage review).
|
||||
2. **Перед каждой Task-инвокацией** прочитайте и выполните pre-spawn-чеклист — [references/git-safety-checklist.md](references/git-safety-checklist.md) §A.
|
||||
3. **После каждой Task-инвокации** прочитайте и выполните post-subagent-чеклист — там же §B.
|
||||
4. **Hard-rule §15.1** — git-коммит-задача = модель Sonnet/Opus, никогда Haiku. Read-only git-операции (`log`, `status`, `diff`, `rev-parse`, `branch --show-current`, `worktree list`) разрешены любой модели.
|
||||
|
||||
Хук `tools/subagent-prompt-prefix.mjs` (зарегистрирован в `.claude/settings.json`) автоматически инжектит git-safety заголовок в каждый Task-prompt — это **первая** линия защиты. Чеклист из этого скила — **вторая** линия (защита со стороны контроллера).
|
||||
|
||||
## Cross-refs
|
||||
|
||||
- Pravila §15.1 — hard-rule субагенты + git.
|
||||
- Spec: `docs/superpowers/specs/2026-05-18-parallel-sessions-coordination-design.md` §5.
|
||||
- Memory: `memory/feedback_subagent_git_reliability.md`.
|
||||
@@ -0,0 +1,65 @@
|
||||
# Git-safety Checklist для контроллера субагентов
|
||||
|
||||
Per Pravila §15.1 — выполнять каждый раз при делегировании задачи через Task tool.
|
||||
|
||||
## §A. Pre-spawn чеклист (до Task-инвокации)
|
||||
|
||||
1. **Резолвите 4 значения** (запишите у себя для post-check):
|
||||
|
||||
```bash
|
||||
git branch --show-current # → ожидаемая ветка
|
||||
git rev-parse HEAD # → pre-spawn parent SHA
|
||||
git rev-parse --show-toplevel # → worktree root
|
||||
pwd # → cwd
|
||||
```
|
||||
|
||||
2. **Выберите модель** субагенту:
|
||||
- Задача требует `git commit`/`push`/`stage`/`checkout`/`switch`/`merge`/`rebase`? → **Sonnet или Opus**, никогда Haiku (§15.1).
|
||||
- Только read-только `git log`/`status`/`diff`/`rev-parse` ИЛИ только Edit/Read/Grep? → любая модель.
|
||||
3. **Если задача правит нормативку из списка §15.2** (Pravila / CLAUDE.md / Tooling / PSR_v1 / MEMORY.md / Открытые_вопросы / docs/adr/* / db/schema.sql):
|
||||
|
||||
```bash
|
||||
git fetch origin && git log HEAD..origin/main --oneline
|
||||
```
|
||||
|
||||
Не пусто → **ребейз/merge до инвокации**, не после. Pre-flight также проверить `docs/sessions/CURRENT.md` на конфликт scope-files / version-claims.
|
||||
|
||||
## §B. Post-subagent чеклист (сразу после возврата субагента)
|
||||
|
||||
1. **`git rev-parse HEAD`** — сравнить с pre-spawn parent SHA.
|
||||
- Равно → субагент не коммитил (OK для Edit-задач без commit).
|
||||
- Отличается ровно одним коммитом, чей parent = pre-spawn HEAD → OK для commit-задач.
|
||||
- **Иначе → STOP, разбор инцидента.**
|
||||
2. **`git branch --show-current`** — сравнить с pre-spawn branch.
|
||||
- Не равно → **STOP, разбор инцидента** (Sprint 6 паттерн).
|
||||
3. **`git log -1 --format='%s%n%P'`** — проверить subject + parent последнего коммита.
|
||||
- Subject соответствует задаче?
|
||||
- Parent = pre-spawn HEAD?
|
||||
4. Если несколько коммитов — ручная проверка subject'ов каждого.
|
||||
|
||||
## §C. Red-flag-список — любой = hard-stop разбор
|
||||
|
||||
- `branch ≠ ожидаемая`;
|
||||
- `parent коммита ≠ pre-spawn HEAD` (висячий коммит / попадание на чужую ветку);
|
||||
- HEAD двинулся, но субагент в отчёте об этом не упомянул;
|
||||
- в diff'е есть файлы вне scope задачи.
|
||||
|
||||
## §D. Обязательный формат отчёта субагента
|
||||
|
||||
Субагент в конце ответа выписывает блок:
|
||||
|
||||
```
|
||||
=== GIT REPORT ===
|
||||
cwd: <pwd>
|
||||
branch: <git branch --show-current>
|
||||
HEAD: <git rev-parse HEAD>
|
||||
HEAD^: <git rev-parse HEAD^>
|
||||
status: <git status --short>
|
||||
=== END GIT REPORT ===
|
||||
```
|
||||
|
||||
Отсутствие блока = контроллер считает результат недостоверным и запускает §B-чеклист сам через Bash.
|
||||
|
||||
## §E. Соотношение с code-review
|
||||
|
||||
Двухстадийное review (Pravila §4.5 / PSR_v1 R10) сохраняется. Git-safety-чеклист **не заменяет** code-review — он стоит **до** него (нет смысла ревьюить diff, если он не в той ветке).
|
||||
@@ -0,0 +1,5 @@
|
||||
# Normalize line endings for Node ESM tooling files.
|
||||
# Keep LF in the working tree regardless of core.autocrlf — CRLF .mjs files
|
||||
# break vitest module loading (SyntaxError: Invalid or unexpected token,
|
||||
# no file:line). See memory quirk #100 (2026-05-19).
|
||||
*.mjs text eol=lf
|
||||
@@ -0,0 +1,31 @@
|
||||
name: brain-l1-watcher (weekly)
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 6 * * 1'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
drift:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
- name: run l1-watcher
|
||||
id: l1
|
||||
run: node tools/l1-watcher.mjs
|
||||
continue-on-error: true
|
||||
- name: open issue on drift
|
||||
if: steps.l1.outcome == 'failure'
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
github.rest.issues.create({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
title: `[l1-watcher] drift detected (weekly cron ${new Date().toISOString().slice(0,10)})`,
|
||||
body: `Run failed. Check workflow logs and run /claude-md-management:claude-md-improver.`,
|
||||
labels: ['brain', 'drift']
|
||||
});
|
||||
+2
-1
@@ -185,5 +185,6 @@ ruflo-mcp-stderr.log
|
||||
.claude/agents/templates/
|
||||
.claude/agents/testing/
|
||||
.claude/agents/v3/
|
||||
.claude/commands/
|
||||
.claude/commands/*
|
||||
!.claude/commands/security-review.md
|
||||
.claude/helpers/
|
||||
|
||||
+4
-1
@@ -98,7 +98,10 @@ paths = [
|
||||
# Vitest-тесты с assertion на mock-данные (mock-телефоны из mockDeals)
|
||||
'''app/tests/Frontend/.*\.(spec|test)\.ts''',
|
||||
# Settings-вкладки с фиктивными mock-данными (профиль/сессии — UI-разводка)
|
||||
'''app/resources/js/views/settings/.*\.vue'''
|
||||
'''app/resources/js/views/settings/.*\.vue''',
|
||||
# Test fixtures for the observer PII filter — contains synthetic JWT / AWS /
|
||||
# Yandex tokens that the filter is supposed to redact. Not real secrets.
|
||||
'''tools/observer-pii-filter\.test\.mjs'''
|
||||
]
|
||||
regexTarget = "match"
|
||||
regexes = [
|
||||
|
||||
@@ -3,3 +3,5 @@ node_modules/
|
||||
bin/
|
||||
CLAUDE.md
|
||||
.claude/skills/mermaid/
|
||||
.claude/skills/ccpm/
|
||||
.claude/skills/data-scientist/
|
||||
|
||||
@@ -10,9 +10,10 @@
|
||||
"type": "http",
|
||||
"url": "https://api.githubcopilot.com/mcp",
|
||||
"headers": {
|
||||
"Authorization": "Bearer ${GITHUB_TOKEN}"
|
||||
"Authorization": "Bearer ${GITHUB_TOKEN}",
|
||||
"X-MCP-Toolsets": "actions,code_security,context,dependabot,discussions,gists,issues,notifications,orgs,projects,pull_requests,repos,secret_protection,security_advisories,stargazers,users"
|
||||
},
|
||||
"comment": "Фаза 0 #3 — официальный hosted GitHub MCP (https://github.com/github/github-mcp-server). Требует env GITHUB_TOKEN с PAT (scopes: repo, read:org, не давать admin/delete). Раньше использовали deprecated @modelcontextprotocol/server-github — заменён 06.05.2026."
|
||||
"comment": "Фаза 0 #3 — официальный hosted GitHub MCP (https://github.com/github/github-mcp-server). Требует env GITHUB_TOKEN с PAT (scopes: repo, read:org, не давать admin/delete). Раньше использовали deprecated @modelcontextprotocol/server-github — заменён 06.05.2026. X-MCP-Toolsets явно перечисляет toolset'ы, включая `projects` (GitHub Projects v2 — доски/спринты/milestones) для раздела C9 «Управление проектами» — план docs/superpowers/plans/2026-05-17-c9-project-management-tooling-integration.md (GH1). Заголовок заменяет default-набор: список явный, чтобы не сузить поверхность."
|
||||
},
|
||||
"laravel-boost": {
|
||||
"command": "php",
|
||||
@@ -38,10 +39,20 @@
|
||||
"args": ["-y", "@modelcontextprotocol/server-redis", "redis://localhost:6379"],
|
||||
"comment": "Off-phase tool — Redis MCP для Memurai (Windows service, Redis 7-совместимый, localhost:6379). Pending формализация в Tooling §3.3 #35 — sync нормативки отдельным планом. Package: @modelcontextprotocol/server-redis@2025.4.25 — DEPRECATED по статусу npm («Package no longer supported»), но Anthropic source, простой протокол, рабочий. Post-MVP migration на community alternative (e.g., @easy-mcps/redis-mcp-server@1.0.8 или @wenit/redis-mcp-server@1.0.3) когда подтвердим trust. READ-ONLY use — отладка очередей, кэша, Pest --parallel race (memory quirk 72). НЕ для prod (нет prod). Если в будущем prod Redis с auth — отдельный entry redis-prod с url через env var."
|
||||
},
|
||||
"ruflo": {
|
||||
"_ruflo_isolated_note": "ruflo MCP-сервер отключён 18.05.2026 (заказчик: «изолируй, не удаляй»). Чтобы вернуть — восстановить блок 'ruflo': { command: 'npx', args: ['-y','ruflo@latest','mcp','start'], comment: ... }. См. memory feedback_ruflo_isolated.md, Tooling §4.10, CLAUDE.md §3.5.",
|
||||
"universal-icons": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "ruflo@latest", "mcp", "start"],
|
||||
"comment": "Off-phase orchestration MCP — exposes ~210 ruflo tools (Core/Intelligence/Agents/Memory/DevTools). Package: ruflo v3.7.0-alpha.38+ MIT (npm `ruflo`, repo ruvnet/claude-flow legacy after rename Jan-2026; plugin namespace @claude-flow/*). Plugin discovery via IPFS (CID QmeXmAdbWVvT84GfDXPD2Vg1HWhiTW2VdZfRLhkS96KkX2) — Pinata+Cloudflare gateways flaky 2026-05-15, only ipfs.io reliable. stdio mode (no port-conflict). Big-bang integration per spec/plan 2026-05-15-ruflo-integration-design.md (commit a68a0a0+). Pending формализация в Tooling §4.10 — Phase 3 Task 3.4."
|
||||
"args": ["-y", "mcp-universal-icons"],
|
||||
"comment": "Off-phase A4 design-tooling #45 — Universal Icons MCP (npm mcp-universal-icons, awssat, MIT). Поиск/вставка SVG-иконок из 10 коллекций, включая Lucide (проектный icon-set, CTO-19). Tools: search_icons / get_icon / health_check. SVG framework-neutral по умолчанию — НЕ запрашивать jsx/Tailwind-формат (PSR_v1 R6.0). Формализация — Tooling §4.20. ADR-006 граница UI2: иконки UI; бренд-логотипы — за 21st logo_search. План docs/superpowers/plans/2026-05-17-a4-design-tooling-integration.md."
|
||||
},
|
||||
"openapi": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@ivotoby/openapi-mcp-server"],
|
||||
"env": {
|
||||
"API_BASE_URL": "http://localhost",
|
||||
"OPENAPI_SPEC_PATH": "./docs/api/openapi.yaml"
|
||||
},
|
||||
"comment": "A3 integration-tooling #47 — OpenAPI MCP (ivo-toby/mcp-openapi-server, @ivotoby/openapi-mcp-server v1.14.0, MIT). Exposes Лидерра REST API endpoints (docs/api/openapi.yaml) as MCP tools. Config via env-vars API_BASE_URL + OPENAPI_SPEC_PATH (stdio transport default). READ scope: API discovery/introspection for Claude Code. Формализован в Tooling §4.22, PSR_v1 R10.1 блок 3, Pravila §13.2."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
.env.production
|
||||
.phpactor.json
|
||||
.phpunit.result.cache
|
||||
/.deptrac.cache
|
||||
/.codex
|
||||
/.cursor/
|
||||
/.idea
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Casts;
|
||||
|
||||
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Eloquent cast for PostgreSQL native INT[] columns.
|
||||
*
|
||||
* Laravel stock 'array' cast uses json_encode/json_decode and sends `[1,2,3]`
|
||||
* (JSON), which Postgres rejects on INT[] columns (expects `{1,2,3}` array
|
||||
* literal). This cast:
|
||||
*
|
||||
* - get(): parses Postgres array literal `{1,2,3}` (or empty `{}`) into PHP
|
||||
* int array.
|
||||
* - set(): serializes PHP array `[1,2,3]` into Postgres literal `{1,2,3}`.
|
||||
*
|
||||
* Used for projects.regions INT[] (Plan 6).
|
||||
*
|
||||
* @implements CastsAttributes<list<int>, list<int>|null>
|
||||
*/
|
||||
class PostgresIntArray implements CastsAttributes
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $attributes
|
||||
* @return list<int>
|
||||
*/
|
||||
public function get(Model $model, string $key, mixed $value, array $attributes): array
|
||||
{
|
||||
if ($value === null || $value === '' || $value === '{}') {
|
||||
return [];
|
||||
}
|
||||
|
||||
// PG returns literal like "{1,2,3}".
|
||||
if (is_string($value)) {
|
||||
$trimmed = trim($value, '{}');
|
||||
|
||||
if ($trimmed === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_map('intval', explode(',', $trimmed));
|
||||
}
|
||||
|
||||
// Defensive: if driver already gave array.
|
||||
if (is_array($value)) {
|
||||
return array_values(array_map('intval', $value));
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
public function set(Model $model, string $key, mixed $value, array $attributes): ?string
|
||||
{
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Defensive: interface phpdoc says list<int>|null, but $value is mixed at PHP level;
|
||||
// protect against runtime misuse (e.g., string passed mistakenly).
|
||||
// @phpstan-ignore function.alreadyNarrowedType
|
||||
if (! is_array($value)) {
|
||||
throw new \InvalidArgumentException(
|
||||
"PostgresIntArray cast expects array for key '{$key}', got ".gettype($value)
|
||||
);
|
||||
}
|
||||
|
||||
if ($value === []) {
|
||||
return '{}';
|
||||
}
|
||||
|
||||
$ints = array_map('intval', $value);
|
||||
|
||||
return '{'.implode(',', $ints).'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Jobs\Supplier\CsvReconcileJob;
|
||||
use App\Models\Project;
|
||||
use App\Models\SupplierManualSyncQueue;
|
||||
use App\Models\SupplierProject;
|
||||
use App\Services\Supplier\Channel\SupplierProjectChannel;
|
||||
use App\Services\Supplier\SupplierExportMode;
|
||||
use App\Services\Supplier\SupplierPortalClient;
|
||||
use App\Support\RussianRegions;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* SaaS-admin → Интеграция с поставщиком: здоровье резервного CSV-канала (Путь 2).
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-18-supplier-csv-reconcile-channel-design.md §4.4
|
||||
*/
|
||||
final class AdminSupplierIntegrationController extends Controller
|
||||
{
|
||||
private const HISTORY_LIMIT = 20;
|
||||
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$rows = DB::connection('pgsql_supplier')
|
||||
->table('supplier_csv_reconcile_log')
|
||||
->orderByDesc('id')
|
||||
->limit(self::HISTORY_LIMIT)
|
||||
->get();
|
||||
|
||||
$last = $rows->first();
|
||||
|
||||
$webhookState = ($last !== null && $last->status === 'drift_alert') ? 'down' : 'live';
|
||||
|
||||
return response()->json([
|
||||
'health' => [
|
||||
'last_run_at' => $last !== null ? ($last->finished_at ?? $last->started_at) : null,
|
||||
'last_status' => $last?->status,
|
||||
'drift_ratio' => $last !== null ? (float) $last->drift_ratio : null,
|
||||
'webhook_state' => $webhookState,
|
||||
],
|
||||
'history' => $rows->map(fn ($r): array => [
|
||||
'started_at' => $r->started_at,
|
||||
'finished_at' => $r->finished_at,
|
||||
'window_start' => $r->window_start,
|
||||
'window_end' => $r->window_end,
|
||||
'status' => $r->status,
|
||||
'total_csv_rows' => (int) $r->total_csv_rows,
|
||||
'matched_count' => (int) $r->matched_count,
|
||||
'recovered_count' => (int) $r->recovered_count,
|
||||
'drift_ratio' => (float) $r->drift_ratio,
|
||||
])->all(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function reconcile(): JsonResponse
|
||||
{
|
||||
CsvReconcileJob::dispatch();
|
||||
|
||||
return response()->json(['dispatched' => true]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Очередь яруса 3 резерва канала миграции проектов — pending-список для
|
||||
* оператора админ-экрана. Spec §4.6.
|
||||
*/
|
||||
public function manualQueueIndex(): JsonResponse
|
||||
{
|
||||
$rows = SupplierManualSyncQueue::where('status', 'pending')
|
||||
->orderByDesc('id')
|
||||
->limit(100)
|
||||
->get(['id', 'project_id', 'platform', 'operation', 'external_id', 'payload_snapshot', 'failure_reason', 'created_at']);
|
||||
|
||||
return response()->json(['queue' => $rows]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Оператор вручную создал проект на портале → reconcile: сверяем через
|
||||
* listProjects(), ставим FK supplier_b{1,2,3}_project_id, помечаем resolved.
|
||||
* 409 если проект на портале не найден (оператор не создал / другие параметры).
|
||||
* Spec §4.6.
|
||||
*/
|
||||
public function manualQueueResolve(int $id, Request $request, SupplierProjectChannel $channel): JsonResponse
|
||||
{
|
||||
$row = SupplierManualSyncQueue::findOrFail($id);
|
||||
if ($row->status !== 'pending') {
|
||||
return response()->json(['message' => 'already resolved or cancelled'], 409);
|
||||
}
|
||||
|
||||
$payload = $row->payload_snapshot;
|
||||
$signalType = (string) ($payload['signal_type'] ?? '');
|
||||
$uniqueKey = (string) ($payload['unique_key'] ?? '');
|
||||
|
||||
$found = null;
|
||||
foreach ($channel->listProjects() as $r) {
|
||||
if (
|
||||
($r['platform'] ?? null) === $row->platform
|
||||
&& ($r['signal_type'] ?? null) === $signalType
|
||||
&& ($r['unique_key'] ?? null) === $uniqueKey
|
||||
) {
|
||||
$found = (int) ($r['id'] ?? 0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($found === null) {
|
||||
return response()->json([
|
||||
'message' => 'Проект не найден на портале поставщика. Проверьте, что вы действительно его создали с теми же параметрами.',
|
||||
], 409);
|
||||
}
|
||||
|
||||
// FK projects.supplier_b{1,2,3}_project_id ведёт на local supplier_projects.id,
|
||||
// не на portal external_id. Find-or-create local row с verified external_id.
|
||||
$sp = SupplierProject::firstOrCreate(
|
||||
[
|
||||
'platform' => $row->platform,
|
||||
'signal_type' => $signalType,
|
||||
'unique_key' => $uniqueKey,
|
||||
],
|
||||
[
|
||||
'supplier_external_id' => (string) $found,
|
||||
'current_limit' => 0,
|
||||
'current_workdays' => [1, 2, 3, 4, 5, 6, 7],
|
||||
'current_regions' => null,
|
||||
'sync_status' => 'ok',
|
||||
],
|
||||
);
|
||||
|
||||
Project::where('id', $row->project_id)->update([
|
||||
'supplier_'.strtolower($row->platform).'_project_id' => $sp->id,
|
||||
]);
|
||||
|
||||
$row->update([
|
||||
'status' => 'resolved',
|
||||
'resolved_by_user_id' => $request->user()->id,
|
||||
'resolved_at' => now(),
|
||||
'external_id' => (string) $found,
|
||||
]);
|
||||
|
||||
return response()->json(['resolved' => true, 'external_id' => $found]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Глобальный режим экспорта проектов поставщику (Plan 4 Task 1).
|
||||
* Spec: docs/superpowers/specs/2026-05-20-project-migration-redesign-design.md §4.1.
|
||||
*/
|
||||
public function getExportMode(): JsonResponse
|
||||
{
|
||||
return response()->json(['mode' => SupplierExportMode::current()]);
|
||||
}
|
||||
|
||||
public function setExportMode(Request $request): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'mode' => ['required', 'in:online,batch'],
|
||||
]);
|
||||
|
||||
DB::table('system_settings')->updateOrInsert(
|
||||
['key' => 'supplier_export_mode'],
|
||||
['value' => $data['mode'], 'type' => 'string', 'updated_at' => now()],
|
||||
);
|
||||
|
||||
return response()->json(['mode' => $data['mode']]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan 4 Task 2: список supplier_projects + кто заказывал (через pivot →
|
||||
* projects → tenants) + дата последней поставки лида.
|
||||
*/
|
||||
public function projectsIndex(): JsonResponse
|
||||
{
|
||||
$rows = DB::table('supplier_projects as sp')
|
||||
->select([
|
||||
'sp.id',
|
||||
'sp.platform',
|
||||
'sp.signal_type',
|
||||
'sp.unique_key',
|
||||
'sp.subject_code',
|
||||
'sp.supplier_external_id',
|
||||
'sp.current_limit',
|
||||
'sp.inactive_since',
|
||||
])
|
||||
->orderBy('sp.unique_key')
|
||||
->orderBy('sp.subject_code')
|
||||
->orderBy('sp.platform')
|
||||
->get();
|
||||
|
||||
$projects = $rows->map(function ($sp): array {
|
||||
$orderers = DB::table('project_supplier_links as psl')
|
||||
->join('projects as p', 'p.id', '=', 'psl.project_id')
|
||||
->join('tenants as t', 't.id', '=', 'p.tenant_id')
|
||||
->where('psl.supplier_project_id', $sp->id)
|
||||
->distinct()
|
||||
->pluck('t.organization_name')
|
||||
->all();
|
||||
|
||||
$lastDelivery = DB::table('supplier_leads')
|
||||
->where('supplier_project_id', $sp->id)
|
||||
->max('received_at');
|
||||
|
||||
$subjectCode = $sp->subject_code !== null ? (int) $sp->subject_code : null;
|
||||
|
||||
return [
|
||||
'id' => (int) $sp->id,
|
||||
'platform' => $sp->platform,
|
||||
'signal_type' => $sp->signal_type,
|
||||
'unique_key' => $sp->unique_key,
|
||||
'subject_code' => $subjectCode,
|
||||
'subject_name' => $subjectCode !== null
|
||||
? (RussianRegions::CODE_TO_NAME[$subjectCode] ?? null)
|
||||
: 'РФ',
|
||||
'current_limit' => (int) $sp->current_limit,
|
||||
'supplier_external_id' => $sp->supplier_external_id,
|
||||
'inactive_since' => $sp->inactive_since,
|
||||
'orderers' => $orderers,
|
||||
'last_delivery_at' => $lastDelivery,
|
||||
];
|
||||
});
|
||||
|
||||
return response()->json(['projects' => $projects->all()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan 4 Task 2: bulk-delete выбранных supplier_projects.
|
||||
* Сначала на портале (deleteProject), затем локально (pivot снимается CASCADE).
|
||||
* Сбой по строке — не прерывает batch, копится в failures[].
|
||||
*/
|
||||
public function projectsDestroy(Request $request, SupplierPortalClient $client): JsonResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'ids' => ['required', 'array', 'min:1'],
|
||||
'ids.*' => ['integer'],
|
||||
]);
|
||||
|
||||
$deleted = 0;
|
||||
$failures = [];
|
||||
|
||||
foreach (SupplierProject::whereIn('id', $data['ids'])->get() as $sp) {
|
||||
try {
|
||||
if ($sp->supplier_external_id !== null) {
|
||||
$client->deleteProject((int) $sp->supplier_external_id);
|
||||
}
|
||||
$sp->delete();
|
||||
$deleted++;
|
||||
} catch (\Throwable $e) {
|
||||
$failures[] = ['id' => $sp->id, 'error' => $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
return response()->json(['deleted' => $deleted, 'failures' => $failures]);
|
||||
}
|
||||
}
|
||||
@@ -63,10 +63,10 @@ class DashboardController extends Controller
|
||||
$curLeads = (clone $base())->whereBetween('received_at', [$windowStart, $now])->count();
|
||||
$prevLeads = (clone $base())->whereBetween('received_at', [$prevStart, $windowStart])->count();
|
||||
|
||||
// --- conversion: % статуса 'paid' в окне ---
|
||||
$curPaid = (clone $base())->where('status', 'paid')
|
||||
// --- conversion: % статуса 'won' в окне ---
|
||||
$curPaid = (clone $base())->where('status', 'won')
|
||||
->whereBetween('received_at', [$windowStart, $now])->count();
|
||||
$prevPaid = (clone $base())->where('status', 'paid')
|
||||
$prevPaid = (clone $base())->where('status', 'won')
|
||||
->whereBetween('received_at', [$prevStart, $windowStart])->count();
|
||||
$curConv = $curLeads > 0 ? round($curPaid / $curLeads * 100, 1) : 0.0;
|
||||
$prevConv = $prevLeads > 0 ? round($prevPaid / $prevLeads * 100, 1) : 0.0;
|
||||
|
||||
@@ -13,6 +13,7 @@ use App\Models\User;
|
||||
use App\Services\SupplierResolver;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
@@ -55,6 +56,11 @@ class DealController extends Controller
|
||||
{
|
||||
$tenantId = (int) $request->user()->tenant_id;
|
||||
|
||||
$request->validate([
|
||||
'received_from' => 'nullable|date',
|
||||
'received_to' => 'nullable|date',
|
||||
]);
|
||||
|
||||
$statuses = (array) $request->query('status_in', []);
|
||||
$projectId = $request->query('project_id') !== null ? (int) $request->query('project_id') : null;
|
||||
$managerId = $request->query('manager_id') !== null ? (int) $request->query('manager_id') : null;
|
||||
@@ -64,6 +70,8 @@ class DealController extends Controller
|
||||
$onlyDeleted = $request->boolean('only_deleted');
|
||||
$countOnly = $request->boolean('count_only');
|
||||
$cursorRaw = (string) $request->query('cursor', '');
|
||||
$receivedFrom = trim((string) $request->query('received_from', ''));
|
||||
$receivedTo = trim((string) $request->query('received_to', ''));
|
||||
|
||||
// Sprint 4 Phase A (audit O-perf-04): keyset pagination через cursor.
|
||||
// При передаче cursor — keyset через PG row constructor (received_at, id) < (?, ?),
|
||||
@@ -81,7 +89,7 @@ class DealController extends Controller
|
||||
$cursor = ['r' => (string) $parsed['r'], 'i' => (int) $parsed['i']];
|
||||
}
|
||||
|
||||
[$deals, $total, $nextCursor] = DB::transaction(function () use ($tenantId, $statuses, $projectId, $managerId, $search, $limit, $offset, $onlyDeleted, $cursor, $countOnly) {
|
||||
[$deals, $total, $nextCursor] = DB::transaction(function () use ($tenantId, $statuses, $projectId, $managerId, $search, $limit, $offset, $onlyDeleted, $cursor, $countOnly, $receivedFrom, $receivedTo) {
|
||||
DB::statement('SET LOCAL app.current_tenant_id = '.$tenantId);
|
||||
|
||||
// Defense-in-depth: явный where(tenant_id) поверх RLS — на тестах
|
||||
@@ -92,8 +100,16 @@ class DealController extends Controller
|
||||
// withTrashed() обходит global scope SoftDeletes; явный
|
||||
// whereNotNull('deleted_at') фильтрует только удалённые.
|
||||
$query = Deal::query()
|
||||
->select('deals.*')
|
||||
->addSelect(['next_reminder_at' => DB::table('reminders')
|
||||
->select('remind_at')
|
||||
->whereColumn('reminders.deal_id', 'deals.id')
|
||||
->whereNull('reminders.completed_at')
|
||||
->orderBy('remind_at')
|
||||
->limit(1),
|
||||
])
|
||||
->where('tenant_id', $tenantId)
|
||||
->with(['project:id,name', 'manager:id,email,first_name,last_name']);
|
||||
->with(['project:id,name,signal_type,signal_identifier,sms_keyword,sms_senders', 'manager:id,email,first_name,last_name']);
|
||||
|
||||
if ($onlyDeleted) {
|
||||
$query->withTrashed()->whereNotNull('deleted_at');
|
||||
@@ -115,6 +131,13 @@ class DealController extends Controller
|
||||
->orWhere('contact_name', 'ilike', $like);
|
||||
});
|
||||
}
|
||||
if ($receivedFrom !== '') {
|
||||
$query->where('received_at', '>=', Carbon::parse($receivedFrom)->startOfDay());
|
||||
}
|
||||
if ($receivedTo !== '') {
|
||||
// received_to включительно — до конца дня (+1 день, строгое <).
|
||||
$query->where('received_at', '<', Carbon::parse($receivedTo)->addDay()->startOfDay());
|
||||
}
|
||||
|
||||
// Audit B2: count_only — отдаём только COUNT(*), пропуская SELECT строк
|
||||
// и cursor/offset-логику (лёгкий запрос для бейджа в сайдбаре).
|
||||
@@ -187,6 +210,15 @@ class DealController extends Controller
|
||||
? ManagerController::formatInitials($d->manager->first_name, $d->manager->last_name, $d->manager->email)
|
||||
: null,
|
||||
'received_at' => $d->received_at?->toIso8601String(),
|
||||
'comment' => $d->comment,
|
||||
'city' => $d->city,
|
||||
'project_signal_type' => $d->project?->signal_type,
|
||||
'project_signal_identifier' => $d->project?->signal_identifier,
|
||||
'project_sms_keyword' => $d->project?->sms_keyword,
|
||||
'project_sms_senders' => $d->project?->sms_senders,
|
||||
'next_reminder_at' => $d->next_reminder_at
|
||||
? Carbon::parse($d->next_reminder_at)->toIso8601String()
|
||||
: null,
|
||||
]),
|
||||
'limit' => $limit,
|
||||
'next_cursor' => $nextCursor,
|
||||
@@ -219,7 +251,7 @@ class DealController extends Controller
|
||||
$deal = Deal::query()
|
||||
->where('tenant_id', $tenantId)
|
||||
->where('id', $id)
|
||||
->with(['project:id,name', 'manager:id,email,first_name,last_name'])
|
||||
->with(['project:id,name,signal_type,signal_identifier,sms_keyword,sms_senders', 'manager:id,email,first_name,last_name'])
|
||||
->first();
|
||||
|
||||
if ($deal === null) {
|
||||
@@ -261,6 +293,10 @@ class DealController extends Controller
|
||||
: null,
|
||||
'received_at' => $deal->received_at?->toIso8601String(),
|
||||
'assigned_at' => $deal->assigned_at?->toIso8601String(),
|
||||
'project_signal_type' => $deal->project?->signal_type,
|
||||
'project_signal_identifier' => $deal->project?->signal_identifier,
|
||||
'project_sms_keyword' => $deal->project?->sms_keyword,
|
||||
'project_sms_senders' => $deal->project?->sms_senders,
|
||||
],
|
||||
'events' => $events->map(fn (ActivityLog $e) => [
|
||||
'id' => $e->id,
|
||||
@@ -403,6 +439,10 @@ class DealController extends Controller
|
||||
'manager_id' => $deal->manager_id,
|
||||
'received_at' => $deal->received_at?->toIso8601String(),
|
||||
'assigned_at' => $deal->assigned_at?->toIso8601String(),
|
||||
'project_signal_type' => $deal->project?->signal_type,
|
||||
'project_signal_identifier' => $deal->project?->signal_identifier,
|
||||
'project_sms_keyword' => $deal->project?->sms_keyword,
|
||||
'project_sms_senders' => $deal->project?->sms_senders,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ namespace App\Http\Controllers\Api;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Deal;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use OpenSpout\Common\Entity\Row;
|
||||
use OpenSpout\Common\Entity\Style\Style;
|
||||
@@ -16,44 +17,45 @@ use OpenSpout\Writer\XLSX\Writer as XlsxWriter;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
* Export сделок в CSV / XLSX через OpenSpout streaming.
|
||||
* Экспорт сделок в CSV / XLSX через OpenSpout streaming.
|
||||
*
|
||||
* Извлечено из DealController (Sprint 3 Phase A, audit O-refactor-01).
|
||||
* Редизайн «Сделки» (2026-05-17, Task A5): экспорт по ДИАПАЗОНУ ДАТ поставки
|
||||
* (received_at), не по списку id. Окно задаётся received_from/received_to;
|
||||
* оба опциональны (пусто = весь период). Колонки соответствуют таблице
|
||||
* страницы (без чекбокса и без «Напоминание» — экспорт = дамп лидов).
|
||||
*
|
||||
* RLS-обёртка SET LOCAL внутри транзакции (PgBouncer-safe).
|
||||
*
|
||||
* J1 (Sprint 3F): auth:sanctum+tenant, tenant_id из auth()->user().
|
||||
*
|
||||
* O-perf-05: streaming устраняет memory pressure. PhpSpreadsheet строил
|
||||
* полный объект .xlsx в памяти (для 10K сделок ≈ 100+ MB). OpenSpout пишет
|
||||
* O-perf-05: streaming устраняет memory pressure. OpenSpout пишет
|
||||
* в php://output постранично через Writer + Row::fromValues и chunkById(500)
|
||||
* по сделкам — пик памяти O(1) от размера экспорта.
|
||||
*
|
||||
* API контракт сохранён:
|
||||
* POST /api/deals/export {ids[], format?: csv|xlsx}
|
||||
* Headers Content-Type / Content-Disposition без изменений.
|
||||
* CSV: UTF-8 + BOM + ;-разделитель (Excel-friendly RU-локаль).
|
||||
* XLSX: bold-header + auto-size columns.
|
||||
*
|
||||
* RLS-обёртка SET LOCAL внутри транзакции (PgBouncer-safe). Чужие id
|
||||
* отфильтрует where(tenant_id) defense-in-depth.
|
||||
*/
|
||||
class DealExportController extends Controller
|
||||
{
|
||||
/** Заголовки таблицы — общие для CSV и XLSX. */
|
||||
private const HEADERS = ['ID', 'Имя', 'Телефон', 'Статус', 'Проект ID', 'Менеджер ID', 'Получено'];
|
||||
/** Заголовки — общие для CSV и XLSX. */
|
||||
private const HEADERS = ['Телефон', 'Источник', 'Город', 'Статус', 'Комментарий', 'Поставлен'];
|
||||
|
||||
/** signal_type → русская метка для колонки «Источник». */
|
||||
private const SIGNAL_LABELS = ['call' => 'Звонки', 'site' => 'Сайт', 'sms' => 'СМС'];
|
||||
|
||||
public function export(Request $request): StreamedResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'ids' => 'required|array|min:1|max:10000',
|
||||
'ids.*' => 'integer|min:1',
|
||||
'received_from' => 'nullable|date',
|
||||
'received_to' => 'nullable|date',
|
||||
'format' => 'nullable|string|in:csv,xlsx',
|
||||
]);
|
||||
|
||||
$tenantId = (int) $request->user()->tenant_id;
|
||||
|
||||
$format = $validated['format'] ?? 'csv';
|
||||
$filename = 'deals_export_'.now()->format('Y-m-d').'.'.$format;
|
||||
$from = isset($validated['received_from']) && $validated['received_from'] !== ''
|
||||
? Carbon::parse($validated['received_from'])->startOfDay() : null;
|
||||
$to = isset($validated['received_to']) && $validated['received_to'] !== ''
|
||||
? Carbon::parse($validated['received_to'])->addDay()->startOfDay() : null;
|
||||
|
||||
$filename = 'deals_export_'.now()->format('Y-m-d').'.'.$format;
|
||||
$headers = $format === 'xlsx'
|
||||
? [
|
||||
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
@@ -64,14 +66,16 @@ class DealExportController extends Controller
|
||||
'Content-Disposition' => 'attachment; filename="'.$filename.'"',
|
||||
];
|
||||
|
||||
return new StreamedResponse(function () use ($validated, $tenantId, $format) {
|
||||
return new StreamedResponse(function () use ($tenantId, $format, $from, $to) {
|
||||
// RLS-контекст должен быть установлен внутри транзакции на момент
|
||||
// фактического SELECT. StreamedResponse callback вызывается уже
|
||||
// после Laravel-response pipeline'а, поэтому открываем транзакцию
|
||||
// прямо здесь.
|
||||
DB::transaction(function () use ($validated, $tenantId, $format) {
|
||||
DB::transaction(function () use ($tenantId, $format, $from, $to) {
|
||||
DB::statement('SET LOCAL app.current_tenant_id = '.$tenantId);
|
||||
|
||||
$statusNames = DB::table('lead_statuses')->pluck('name_ru', 'slug');
|
||||
|
||||
$writer = $this->openWriter($format);
|
||||
$writer->openToFile('php://output');
|
||||
|
||||
@@ -81,32 +85,41 @@ class DealExportController extends Controller
|
||||
if ($format === 'xlsx') {
|
||||
/** @var XlsxWriter $writer */
|
||||
$writer->getCurrentSheet()->setName('Сделки');
|
||||
$headerStyle = (new Style)->withFontBold(true);
|
||||
$writer->addRow(Row::fromValuesWithStyle(self::HEADERS, $headerStyle));
|
||||
$writer->addRow(Row::fromValuesWithStyle(self::HEADERS, (new Style)->withFontBold(true)));
|
||||
} else {
|
||||
$writer->addRow(Row::fromValues(self::HEADERS));
|
||||
}
|
||||
|
||||
// chunkById(500) — keyset-friendly; в нашем DealsView это
|
||||
// редкий тяжёлый action, экспортировать могут до 10K id.
|
||||
Deal::query()
|
||||
$query = Deal::query()
|
||||
->where('tenant_id', $tenantId)
|
||||
->whereIn('id', $validated['ids'])
|
||||
->orderBy('id')
|
||||
->chunkById(500, function ($deals) use ($writer) {
|
||||
foreach ($deals as $deal) {
|
||||
/** @var Deal $deal */
|
||||
$writer->addRow(Row::fromValues([
|
||||
$deal->id,
|
||||
(string) ($deal->contact_name ?? ''),
|
||||
(string) $deal->phone,
|
||||
(string) $deal->status,
|
||||
$deal->project_id,
|
||||
$deal->manager_id ?? '',
|
||||
$deal->received_at->toDateTimeString(),
|
||||
]));
|
||||
}
|
||||
});
|
||||
->with('project:id,name,signal_type')
|
||||
->orderByDesc('received_at');
|
||||
|
||||
if ($from !== null) {
|
||||
$query->where('received_at', '>=', $from);
|
||||
}
|
||||
if ($to !== null) {
|
||||
$query->where('received_at', '<', $to);
|
||||
}
|
||||
|
||||
// chunkById(500) — keyset-friendly; deals.id — BIGSERIAL (unique),
|
||||
// корректно для чанкинга даже при партиционированной PK (id, received_at).
|
||||
$query->chunkById(500, function ($deals) use ($writer, $statusNames) {
|
||||
foreach ($deals as $deal) {
|
||||
/** @var Deal $deal */
|
||||
$signal = $deal->project?->signal_type;
|
||||
$source = trim(($deal->project?->name ?? '—').' · '
|
||||
.(self::SIGNAL_LABELS[$signal] ?? '—'));
|
||||
$writer->addRow(Row::fromValues([
|
||||
(string) $deal->phone,
|
||||
$source,
|
||||
(string) ($deal->city ?? ''),
|
||||
(string) ($statusNames[$deal->status] ?? $deal->status),
|
||||
(string) ($deal->comment ?? ''),
|
||||
$deal->received_at?->toDateTimeString() ?? '',
|
||||
]));
|
||||
}
|
||||
}, 'id');
|
||||
|
||||
$writer->close();
|
||||
});
|
||||
@@ -120,12 +133,10 @@ class DealExportController extends Controller
|
||||
}
|
||||
|
||||
// CSV: ;-разделитель + UTF-8 BOM (Excel-friendly RU-локаль).
|
||||
$options = new CsvOptions(
|
||||
return new CsvWriter(new CsvOptions(
|
||||
FIELD_DELIMITER: ';',
|
||||
FIELD_ENCLOSURE: '"',
|
||||
SHOULD_ADD_BOM: true,
|
||||
);
|
||||
|
||||
return new CsvWriter($options);
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,10 +32,17 @@ class BulkProjectActionRequest extends FormRequest
|
||||
'scope.filter.search' => ['nullable', 'string', 'max:255'],
|
||||
];
|
||||
|
||||
if ($action === 'update_regions' || $action === 'update_days') {
|
||||
$maxMask = $action === 'update_regions' ? 255 : 127;
|
||||
$rules['add'] = ['nullable', 'integer', 'min:0', "max:{$maxMask}"];
|
||||
$rules['remove'] = ['nullable', 'integer', 'min:0', "max:{$maxMask}"];
|
||||
if ($action === 'update_regions') {
|
||||
// Plan 6.5: субъект-уровневые коды 1..89 (см. resources/js/constants/regions.ts).
|
||||
$rules['add_regions'] = ['nullable', 'array'];
|
||||
$rules['add_regions.*'] = ['integer', 'between:1,89'];
|
||||
$rules['remove_regions'] = ['nullable', 'array'];
|
||||
$rules['remove_regions.*'] = ['integer', 'between:1,89'];
|
||||
}
|
||||
|
||||
if ($action === 'update_days') {
|
||||
$rules['add'] = ['nullable', 'integer', 'min:0', 'max:127'];
|
||||
$rules['remove'] = ['nullable', 'integer', 'min:0', 'max:127'];
|
||||
}
|
||||
|
||||
if ($action === 'update_limit') {
|
||||
|
||||
@@ -22,8 +22,11 @@ class StoreProjectRequest extends FormRequest
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'signal_type' => ['required', Rule::in(['site', 'call', 'sms'])],
|
||||
'daily_limit_target' => ['required', 'integer', 'min:1', 'max:10000'],
|
||||
'region_mask' => ['required', 'integer', 'min:0'],
|
||||
'region_mode' => ['required', Rule::in(['include', 'exclude'])],
|
||||
// Plan 6: subject-level regions[] заменил region_mask/region_mode на API-уровне.
|
||||
// Empty array = "вся РФ" (паритет с legacy region_mask=255 + region_mode='include').
|
||||
// present = поле должно быть в payload (даже если []), enforces explicit choice.
|
||||
'regions' => ['present', 'array'],
|
||||
'regions.*' => ['integer', 'between:1,89'],
|
||||
'delivery_days_mask' => ['required', 'integer', 'min:1', 'max:127'],
|
||||
];
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Models\Project;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class UpdateProjectRequest extends FormRequest
|
||||
{
|
||||
@@ -17,15 +17,35 @@ class UpdateProjectRequest extends FormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
// signal_type immutable: не валидируется в правилах, controller игнорирует поле
|
||||
return [
|
||||
$rules = [
|
||||
'name' => ['sometimes', 'string', 'max:255'],
|
||||
'daily_limit_target' => ['sometimes', 'integer', 'min:1', 'max:10000'],
|
||||
'region_mask' => ['sometimes', 'integer', 'min:0'],
|
||||
'region_mode' => ['sometimes', Rule::in(['include', 'exclude'])],
|
||||
// Plan 6: subject-level regions[] заменил region_mask/region_mode на API-уровне.
|
||||
// sometimes = поле omit-able (preserves prior DB value), массив + each 1..89.
|
||||
'regions' => ['sometimes', 'array'],
|
||||
'regions.*' => ['integer', 'between:1,89'],
|
||||
'delivery_days_mask' => ['sometimes', 'integer', 'min:1', 'max:127'],
|
||||
'sms_senders' => ['sometimes', 'array', 'min:1'],
|
||||
'sms_senders.*' => ['string', 'max:11'],
|
||||
'sms_keyword' => ['sometimes', 'nullable', 'string', 'min:1', 'max:50'],
|
||||
];
|
||||
|
||||
// 18.05.2026 UX: редактирование источника (signal_identifier) для site/call.
|
||||
// Регулярки соответствуют StoreProjectRequest (domain + 7\d{10}).
|
||||
// signal_type immutable — берём из текущего проекта по route id.
|
||||
$projectId = $this->route('id');
|
||||
if ($projectId !== null) {
|
||||
$project = Project::find($projectId);
|
||||
if ($project !== null) {
|
||||
if ($project->signal_type === 'site') {
|
||||
$rules['signal_identifier'] = ['sometimes', 'string', 'regex:/^[a-z0-9][a-z0-9\-]*(\.[a-z0-9][a-z0-9\-]*)*\.[a-z]{2,}$/i'];
|
||||
} elseif ($project->signal_type === 'call') {
|
||||
$rules['signal_identifier'] = ['sometimes', 'string', 'regex:/^7\d{10}$/'];
|
||||
}
|
||||
// sms: signal_identifier меняется через sms_senders/sms_keyword (см. выше)
|
||||
}
|
||||
}
|
||||
|
||||
return $rules;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ class ProjectResource extends JsonResource
|
||||
'archived_at' => $project->archived_at?->toIso8601String(),
|
||||
'region_mask' => $this->region_mask,
|
||||
'region_mode' => $this->region_mode,
|
||||
'regions' => $this->regions,
|
||||
'delivery_days_mask' => $this->delivery_days_mask,
|
||||
'sync_status' => $this->aggregateSyncStatus(),
|
||||
'last_synced_at' => $this->aggregateLastSyncedAt(),
|
||||
|
||||
@@ -12,8 +12,10 @@ use App\Models\SupplierLead;
|
||||
use App\Models\Tenant;
|
||||
use App\Services\Billing\LedgerService;
|
||||
use App\Services\DuplicateDetector;
|
||||
use App\Services\LeadDistributor;
|
||||
use App\Services\LeadRouter;
|
||||
use App\Services\NotificationService;
|
||||
use App\Services\RegionTagResolver;
|
||||
use App\Services\SupplierProjects\SupplierProjectResolver;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
@@ -86,6 +88,8 @@ class RouteSupplierLeadJob implements ShouldQueue
|
||||
DuplicateDetector $duplicateDetector,
|
||||
NotificationService $notifier,
|
||||
LedgerService $ledger,
|
||||
LeadDistributor $distributor,
|
||||
RegionTagResolver $tagResolver,
|
||||
): void {
|
||||
$lead = SupplierLead::findOrFail($this->supplierLeadId);
|
||||
|
||||
@@ -108,20 +112,19 @@ class RouteSupplierLeadJob implements ShouldQueue
|
||||
$supplier = $resolver->resolveOrStub($platform, $signalType, $identifier);
|
||||
$lead->update(['supplier_project_id' => $supplier->id]);
|
||||
|
||||
$matched = $router->matchEligibleProjects($supplier, (string) $lead->phone);
|
||||
$matched = $router->matchEligibleProjects($supplier);
|
||||
$selected = $distributor->selectRecipients($matched); // cap=3 случайных
|
||||
|
||||
$subjectCode = $tagResolver->resolve((string) ($lead->raw_payload['tag'] ?? ''));
|
||||
|
||||
$createdCount = 0;
|
||||
$failures = [];
|
||||
foreach ($matched as $project) {
|
||||
foreach ($selected as $project) {
|
||||
try {
|
||||
if ($this->createDealCopyForProject($lead, $project, $duplicateDetector, $notifier, $ledger)) {
|
||||
if ($this->createDealCopyForProject($lead, $project, $duplicateDetector, $notifier, $ledger, $subjectCode)) {
|
||||
$createdCount++;
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
// Per-Project failure isolation (Plan 2 code-review Important).
|
||||
// Sharing-model: один сбой проекта не должен абортить routing других tenant'ов.
|
||||
// Логируем и продолжаем; final failed() callback зафиксирует общий проблемный лид
|
||||
// только если ВСЕ Projects упали (через handle() rethrow ниже).
|
||||
$failures[] = ['project_id' => $project->id, 'tenant_id' => $project->tenant_id, 'error' => $e->getMessage()];
|
||||
Log::warning('supplier_lead.per_project_routing_failed', [
|
||||
'supplier_lead_id' => $lead->id,
|
||||
@@ -132,9 +135,7 @@ class RouteSupplierLeadJob implements ShouldQueue
|
||||
}
|
||||
}
|
||||
|
||||
// Если ВСЕ Projects упали (а matched был непустой) — пробрасываем последнюю ошибку,
|
||||
// чтобы failed() callback сработал и проблема ушла в failed_webhook_jobs.
|
||||
if ($matched->isNotEmpty() && $createdCount === 0 && count($failures) === $matched->count()) {
|
||||
if ($selected->isNotEmpty() && $createdCount === 0 && count($failures) === $selected->count()) {
|
||||
throw new RuntimeException(
|
||||
'All eligible projects failed routing for supplier_lead='.$lead->id.
|
||||
'; last error: '.($failures[array_key_last($failures)]['error'] ?? 'unknown')
|
||||
@@ -150,7 +151,10 @@ class RouteSupplierLeadJob implements ShouldQueue
|
||||
/**
|
||||
* Парсит поле raw_payload['project'] (формат `B[123]_<rest>`):
|
||||
* - rest вида `7\d{10}` → call (телефон-номер для звонка-сигнала);
|
||||
* - rest вида `^[a-z0-9-]+(\.[a-z0-9-]+)+$` → site (домен сайта-сигнала);
|
||||
* - rest вида `^[a-z0-9-]+(\.[a-z0-9-]+)+$` → site (rest целиком — домен);
|
||||
* - rest со встроенным доменом в свободном тексте → site (identifier =
|
||||
* извлечённый домен; поставщик иногда шлёт имя вида `заявка carmoney.ru/`
|
||||
* или `Платежи cabinet.caranga.ru/login` — регрессия 18.05.2026, 21 лид);
|
||||
* - иначе → sms (короткое имя отправителя SMS-шлюза).
|
||||
*
|
||||
* @return array{0: string, 1: string, 2: string} [platform, signal_type, identifier]
|
||||
@@ -163,15 +167,26 @@ class RouteSupplierLeadJob implements ShouldQueue
|
||||
$platform = $m[1];
|
||||
$rest = $m[2];
|
||||
|
||||
// Домен с латинским TLD ≥2 букв (последний сегмент — только буквы), допускается
|
||||
// в любой позиции строки. Соответствует чистому rest и встроенному в текст домену.
|
||||
$domainRe = '/(?<![a-z0-9.\-])([a-z0-9][a-z0-9\-]*(?:\.[a-z0-9][a-z0-9\-]*)*\.[a-z]{2,})/i';
|
||||
|
||||
if (preg_match('/^7\d{10}$/', $rest) === 1) {
|
||||
$signalType = 'call';
|
||||
$identifier = $rest;
|
||||
} elseif (preg_match('/^[a-z0-9-]+(\.[a-z0-9-]+)+$/i', $rest) === 1) {
|
||||
$signalType = 'site';
|
||||
$identifier = $rest;
|
||||
} elseif (preg_match($domainRe, $rest, $dm) === 1) {
|
||||
// Домен извлечён из свободного текста — это сайт-сигнал.
|
||||
$signalType = 'site';
|
||||
$identifier = mb_strtolower($dm[1]);
|
||||
} else {
|
||||
$signalType = 'sms';
|
||||
$identifier = $rest;
|
||||
}
|
||||
|
||||
return [$platform, $signalType, $rest];
|
||||
return [$platform, $signalType, $identifier];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -185,9 +200,10 @@ class RouteSupplierLeadJob implements ShouldQueue
|
||||
DuplicateDetector $duplicateDetector,
|
||||
NotificationService $notifier,
|
||||
LedgerService $ledger,
|
||||
?int $subjectCode,
|
||||
): bool {
|
||||
try {
|
||||
return DB::transaction(function () use ($lead, $project, $duplicateDetector, $notifier, $ledger): bool {
|
||||
return DB::transaction(function () use ($lead, $project, $duplicateDetector, $notifier, $ledger, $subjectCode): bool {
|
||||
DB::statement("SET LOCAL app.current_tenant_id = '{$project->tenant_id}'");
|
||||
|
||||
/** @var Tenant $tenant */
|
||||
@@ -238,6 +254,7 @@ class RouteSupplierLeadJob implements ShouldQueue
|
||||
'phones' => $phones,
|
||||
'status' => 'new',
|
||||
'received_at' => $receivedAt,
|
||||
'subject_code' => $subjectCode,
|
||||
]);
|
||||
|
||||
$master = $duplicateDetector->findMaster(
|
||||
|
||||
@@ -24,21 +24,20 @@ use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Hourly CSV reconciliation с порталом поставщика.
|
||||
* Резервный CSV-канал (Путь 2): сверка отчёта поставщика «Запрос номеров»
|
||||
* с принятыми webhook-лидами; recovery пропущенного + drift-детект.
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-11-plan4-billing-csv-admin-design.md §5.3
|
||||
* Spec: docs/superpowers/specs/2026-05-18-supplier-csv-reconcile-channel-design.md
|
||||
*
|
||||
* Алгоритм:
|
||||
* 1. Cache::lock на 600s — overlap-защита.
|
||||
* 1. Cache::lock — overlap-защита.
|
||||
* 2. INSERT supplier_csv_reconcile_log (status='running').
|
||||
* 3. Download CSV за окно 25h.
|
||||
* 4. Parse → собираем ['vid' => row].
|
||||
* 5. SELECT existing vid'ы из supplier_leads (BYPASSRLS).
|
||||
* 6. Diff = missing.
|
||||
* 7. Для каждой missing — INSERT supplier_leads (recovered_from_csv_at) + dispatch RouteJob.
|
||||
* 8. UPDATE log с метриками + status.
|
||||
* 9. drift > 5% → CsvDriftAlertMail + alert_email_sent_at.
|
||||
* 10. На exception — status='failed', throw.
|
||||
* 3. Заказать отчёт «Запрос номеров» за окно (2 кал. дня) → дождаться → скачать.
|
||||
* 4. Parse CSV (Name;Tag;Phone).
|
||||
* 5. Дедуп по (phone, project): SELECT existing supplier_leads за окно.
|
||||
* 6. Diff = missing → INSERT supplier_leads (vid=NULL, source='csv_recovery') + RouteJob.
|
||||
* 7. UPDATE log + drift; drift > 5% → CsvDriftAlertMail.
|
||||
* 8. На exception — status='failed', throw (cron повторит через 30 мин).
|
||||
*/
|
||||
final class CsvReconcileJob implements ShouldQueue
|
||||
{
|
||||
@@ -55,7 +54,7 @@ final class CsvReconcileJob implements ShouldQueue
|
||||
|
||||
private const DRIFT_THRESHOLD = 0.05;
|
||||
|
||||
private const WINDOW_HOURS = 25;
|
||||
private const WINDOW_DAYS = 2;
|
||||
|
||||
private const LOCK_NAME = 'supplier:csv_reconcile';
|
||||
|
||||
@@ -75,47 +74,63 @@ final class CsvReconcileJob implements ShouldQueue
|
||||
return;
|
||||
}
|
||||
|
||||
// Окно: начало (сегодня − (WINDOW_DAYS−1) дней) 00:00 .. сейчас.
|
||||
$windowEnd = Carbon::now();
|
||||
$windowStart = (clone $windowEnd)->subHours(self::WINDOW_HOURS);
|
||||
$windowStart = Carbon::today()->subDays(self::WINDOW_DAYS - 1);
|
||||
|
||||
$logId = DB::connection(self::DB_CONNECTION)
|
||||
->table('supplier_csv_reconcile_log')
|
||||
->insertGetId([
|
||||
'started_at' => now(),
|
||||
'window_start' => $windowStart,
|
||||
'window_end' => $windowEnd,
|
||||
'status' => 'running',
|
||||
'created_at' => now(),
|
||||
]);
|
||||
// $logId инициализируется внутри try: если сам insertGetId упадёт (БД недоступна),
|
||||
// catch обязан НЕ обращаться к неинициализированному $logId, а finally — освободить
|
||||
// lock (иначе lock висит LOCK_TTL_SECONDS и пропускает следующие запуски).
|
||||
$logId = null;
|
||||
|
||||
try {
|
||||
$csv = $portal->downloadLeadsCsv($windowStart, $windowEnd);
|
||||
$logId = DB::connection(self::DB_CONNECTION)
|
||||
->table('supplier_csv_reconcile_log')
|
||||
->insertGetId([
|
||||
'started_at' => now(),
|
||||
'window_start' => $windowStart,
|
||||
'window_end' => $windowEnd,
|
||||
'status' => 'running',
|
||||
'created_at' => now(),
|
||||
]);
|
||||
|
||||
/** @var array<string, array<string, mixed>> $csvByVid */
|
||||
$csvByVid = [];
|
||||
$reportId = $portal->requestNumbersReport($windowStart, $windowEnd);
|
||||
$portal->waitReportReady($reportId);
|
||||
$csv = $portal->downloadReport($reportId);
|
||||
|
||||
// CSV-строки по ключу phone|project (последняя строка с тем же ключом перетирает).
|
||||
/** @var array<string, array{project: string, tag: string, phone: string}> $csvByKey */
|
||||
$csvByKey = [];
|
||||
foreach ($parser->parse($csv) as $row) {
|
||||
$csvByVid[(string) $row['vid']] = $row;
|
||||
$csvByKey[$this->dedupKey((string) $row['phone'], (string) $row['project'])] = $row;
|
||||
}
|
||||
$totalCsvRows = count($csvByVid);
|
||||
$totalCsvRows = count($csvByKey);
|
||||
|
||||
$existing = DB::connection(self::DB_CONNECTION)
|
||||
// Существующие лиды за окно → set ключей phone|project.
|
||||
$existingKeys = [];
|
||||
DB::connection(self::DB_CONNECTION)
|
||||
->table('supplier_leads')
|
||||
->where('received_at', '>=', $windowStart)
|
||||
->where('received_at', '<', $windowEnd->copy()->addHour())
|
||||
->pluck('vid')
|
||||
->map(fn ($v) => (string) $v)
|
||||
->all();
|
||||
->select('phone', 'raw_payload')
|
||||
->orderBy('id')
|
||||
->chunk(500, function ($leads) use (&$existingKeys): void {
|
||||
foreach ($leads as $lead) {
|
||||
$payload = is_string($lead->raw_payload)
|
||||
? json_decode($lead->raw_payload, true)
|
||||
: (array) $lead->raw_payload;
|
||||
$project = (string) ($payload['project'] ?? '');
|
||||
$existingKeys[$this->dedupKey((string) $lead->phone, $project)] = true;
|
||||
}
|
||||
});
|
||||
|
||||
$existingMap = array_flip($existing);
|
||||
$missing = array_diff_key($csvByVid, $existingMap);
|
||||
$missing = array_diff_key($csvByKey, $existingKeys);
|
||||
|
||||
$recoveredCount = 0;
|
||||
foreach ($missing as $vid => $row) {
|
||||
$platform = $this->extractPlatform((string) ($row['project'] ?? ''));
|
||||
foreach ($missing as $row) {
|
||||
$platform = $this->extractPlatform((string) $row['project']);
|
||||
if ($platform === null) {
|
||||
Log::warning('csv_reconcile.unparseable_project_skipped', [
|
||||
'vid' => $vid,
|
||||
'project' => $row['project'] ?? null,
|
||||
'project' => $row['project'],
|
||||
]);
|
||||
|
||||
continue;
|
||||
@@ -123,24 +138,23 @@ final class CsvReconcileJob implements ShouldQueue
|
||||
|
||||
try {
|
||||
$lead = SupplierLead::create([
|
||||
'vid' => (int) $vid,
|
||||
'vid' => null,
|
||||
'platform' => $platform,
|
||||
'phone' => (string) $row['phone'],
|
||||
'raw_payload' => $row,
|
||||
'received_at' => Carbon::createFromTimestamp((int) $row['time']),
|
||||
'received_at' => now(),
|
||||
'recovered_from_csv_at' => now(),
|
||||
'source' => 'csv_recovery',
|
||||
'supplier_project_id' => null, // ResolverStub разрезолвит при RouteJob run
|
||||
'supplier_project_id' => null,
|
||||
]);
|
||||
RouteSupplierLeadJob::dispatch($lead->id);
|
||||
$recoveredCount++;
|
||||
} catch (QueryException $e) {
|
||||
if (str_contains($e->getMessage(), 'unique')) {
|
||||
Log::info('csv_reconcile.duplicate_vid_skipped', ['vid' => $vid]);
|
||||
|
||||
continue;
|
||||
}
|
||||
throw $e;
|
||||
Log::warning('csv_reconcile.lead_insert_failed', [
|
||||
'phone' => $row['phone'],
|
||||
'project' => $row['project'],
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,14 +191,17 @@ final class CsvReconcileJob implements ShouldQueue
|
||||
->update($update);
|
||||
|
||||
} catch (Throwable $e) {
|
||||
DB::connection(self::DB_CONNECTION)
|
||||
->table('supplier_csv_reconcile_log')
|
||||
->where('id', $logId)
|
||||
->update([
|
||||
'finished_at' => now(),
|
||||
'status' => 'failed',
|
||||
'error_message' => substr($e->getMessage(), 0, 1000),
|
||||
]);
|
||||
// $logId === null — упал сам insertGetId, log-строки нет, обновлять нечего.
|
||||
if ($logId !== null) {
|
||||
DB::connection(self::DB_CONNECTION)
|
||||
->table('supplier_csv_reconcile_log')
|
||||
->where('id', $logId)
|
||||
->update([
|
||||
'finished_at' => now(),
|
||||
'status' => 'failed',
|
||||
'error_message' => substr($e->getMessage(), 0, 1000),
|
||||
]);
|
||||
}
|
||||
throw $e;
|
||||
} finally {
|
||||
$lock->release();
|
||||
@@ -192,8 +209,15 @@ final class CsvReconcileJob implements ShouldQueue
|
||||
}
|
||||
|
||||
/**
|
||||
* Извлекает platform (B1/B2/B3) из поля raw_payload['project'] CSV-строки.
|
||||
* Формат project: `B[123]_<rest>` (например `B1_a.com`, `B2_79991234567`).
|
||||
* Ключ дедупа: нормализованный phone + project.
|
||||
*/
|
||||
private function dedupKey(string $phone, string $project): string
|
||||
{
|
||||
return trim($phone).'|'.trim($project);
|
||||
}
|
||||
|
||||
/**
|
||||
* Извлекает platform (B1/B2/B3) из имени проекта формата `B[123]_<rest>`.
|
||||
* Возвращает null если не парсится — caller пропустит строку с warning.
|
||||
*/
|
||||
private function extractPlatform(string $project): ?string
|
||||
|
||||
@@ -12,46 +12,55 @@ use App\Mail\SupplierCriticalAlertMail;
|
||||
use App\Models\Project;
|
||||
use App\Models\SupplierProject;
|
||||
use App\Models\SupplierSyncLog;
|
||||
use App\Services\Supplier\Channel\Exceptions\TierEscalatedException;
|
||||
use App\Services\Supplier\Channel\Exceptions\WindowDeferredException;
|
||||
use App\Services\Supplier\Channel\SupplierProjectChannel;
|
||||
use App\Services\Supplier\Dto\SupplierProjectDto;
|
||||
use App\Services\Supplier\SupplierPortalClient;
|
||||
use App\Services\Supplier\SupplierProjectGrouping;
|
||||
use App\Services\Supplier\SupplierQuotaAllocator;
|
||||
use App\Support\RussianRegions;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use stdClass;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Daily 20:30 МСК cron-job: синхронизирует supplier_projects с поставщиком crm.bp-gr.ru.
|
||||
* Daily 18:00 МСК cron-job: синхронизирует supplier_projects с поставщиком crm.bp-gr.ru
|
||||
* (расписание перенесено 20:30 → 18:00, см. routes/console.php).
|
||||
*
|
||||
* Алгоритм (per spec §4.3):
|
||||
* 1. Итерация по всем активным (inactive_since IS NULL) supplier_projects.
|
||||
* 2. Для каждого:
|
||||
* a. Подтянуть активные Лидерра-projects через FK supplier_b{1,2,3}_project_id.
|
||||
* b. Адаптировать в plain stdClass с полями daily_limit/workdays/regions.
|
||||
* c. Вызвать SupplierQuotaAllocator::allocate() — pure distribution.
|
||||
* d. Сравнить с current state через SupplierProjectDto::equals(); skip if no diff.
|
||||
* e. saveProject() при supplier_external_id=null, иначе updateProject().
|
||||
* f. Записать audit row в supplier_sync_log.
|
||||
* 3. Failure-handling:
|
||||
* - SupplierAuthException → SupplierCriticalAlertMail('sticky_auth') + Sentry + throw.
|
||||
* - SupplierTransientException → log + continue. После 50 подряд → mass_transient alert + break.
|
||||
* - SupplierClientException → log + continue.
|
||||
* 4. Time budget cutoff: после 20:55 МСК прервать loop (буфер 5 мин до 21:00).
|
||||
* Алгоритм (план 3 Task 5 → переработан: one-group-per-identifier):
|
||||
* 1. Загрузить активные Лидерра-projects (is_active=true, archived_at IS NULL).
|
||||
* 2. Сгруппировать по (signal_type, identifier) — БЕЗ subject_code:
|
||||
* - identifier = buildUniqueKeyAgnostic() (site/call → signal_identifier; sms+keyword → sender+keyword; sms → sender).
|
||||
* - platforms = resolvePlatforms() (site/call → B1+B2+B3; sms+keyword → B2+B3; sms → B3).
|
||||
* - merged_regions = union(project.regions) по всем проектам группы.
|
||||
* Если хотя бы один проект имеет regions=[] («Вся РФ»), merged_regions=[].
|
||||
* 3. Для каждой группы:
|
||||
* - eligible-today проекты группы (workday-маска на завтра).
|
||||
* - order = computeOrder($eligibleLimits); workdays = union.
|
||||
* - tag = name региона если один, иначе «РФ».
|
||||
* - Найти существующие supplier_projects (unique_key, signal_type, platform) — без subject_code-фильтра:
|
||||
* - Нет → saveProjectMultiFlag → [platform → id] → upsert supplier_projects (subject_code=null).
|
||||
* - Есть → partial-set recovery + updateProject каждого с актуальными regions/limit.
|
||||
* - Pivot: project × supplier_project → INSERT ... ON CONFLICT DO NOTHING (subject_code=null).
|
||||
* 4. Failure-handling (Auth/Transient/Client/Window/TierEscalated), time-budget cutoff — сохранены.
|
||||
*
|
||||
* NOTE про connection: Job's $connection — это queue connection, не DB. Используем
|
||||
* Eloquent::on('pgsql_supplier') для cross-tenant видимости (Plan 3 Task 3 learning).
|
||||
* Портальное ограничение: один identifier = одна группа B1/B2/B3 (status=Doubles на дублирование).
|
||||
* Поэтому все регионы проекта передаются одним списком — portal фильтрует оба одновременно.
|
||||
*
|
||||
* NOTE про connection: Eloquent::on('pgsql_supplier') для cross-tenant видимости.
|
||||
*
|
||||
* Spec:
|
||||
* - docs/superpowers/specs/2026-05-10-supplier-integration-design.md §4.3-§4.4
|
||||
* - docs/superpowers/specs/2026-05-11-plan3-supplier-sync-design.md §4
|
||||
* - docs/superpowers/specs/2026-05-20-project-migration-redesign-design.md §4.3
|
||||
* - docs/superpowers/plans/2026-05-20-project-migration-redesign-plan-3-export.md Task 5
|
||||
*/
|
||||
class SyncSupplierProjectsJob implements ShouldQueue
|
||||
{
|
||||
@@ -63,27 +72,84 @@ class SyncSupplierProjectsJob implements ShouldQueue
|
||||
|
||||
public const DB_CONNECTION = 'pgsql_supplier';
|
||||
|
||||
public function handle(?SupplierPortalClient $client = null): void
|
||||
private SupplierProjectChannel $channel;
|
||||
|
||||
private SupplierPortalClient $client;
|
||||
|
||||
public function handle(?SupplierProjectChannel $channel = null): void
|
||||
{
|
||||
$client ??= app(SupplierPortalClient::class);
|
||||
$this->channel = $channel ?? app(SupplierProjectChannel::class);
|
||||
$this->client = app(SupplierPortalClient::class);
|
||||
$consecutiveTransient = 0;
|
||||
|
||||
$projects = SupplierProject::on(self::DB_CONNECTION)
|
||||
->whereNull('inactive_since')
|
||||
// 1. Load active Лидерра-projects via pgsql_supplier
|
||||
/** @var Collection<int, Project> $projects */
|
||||
$projects = Project::on(self::DB_CONNECTION)
|
||||
->where('is_active', true)
|
||||
->whereNull('archived_at')
|
||||
->orderBy('id')
|
||||
->get();
|
||||
|
||||
foreach ($projects as $sp) {
|
||||
// 2. Group by (signal_type, identifier) — no subject_code split.
|
||||
// Portal constraint: one identifier = one B1/B2/B3 group (status=Doubles on duplicate name).
|
||||
// group key => [ 'signal_type', 'identifier', 'merged_regions', 'platforms', 'projects' => [...] ]
|
||||
/** @var array<string, array{signal_type: string, identifier: string, merged_regions: list<int>, has_all_russia: bool, platforms: list<string>, projects: list<Project>}> $groups */
|
||||
$groups = [];
|
||||
|
||||
foreach ($projects as $project) {
|
||||
$platforms = SupplierProjectGrouping::resolvePlatforms($project);
|
||||
if ($platforms === []) {
|
||||
continue;
|
||||
}
|
||||
$identifier = SupplierProjectGrouping::buildUniqueKeyAgnostic($project);
|
||||
|
||||
$key = $project->signal_type.'|'.$identifier;
|
||||
if (! isset($groups[$key])) {
|
||||
$groups[$key] = [
|
||||
'signal_type' => (string) $project->signal_type,
|
||||
'identifier' => $identifier,
|
||||
'merged_regions' => [],
|
||||
'has_all_russia' => false,
|
||||
'platforms' => $platforms,
|
||||
'projects' => [],
|
||||
];
|
||||
}
|
||||
// Merge regions — union across all projects in this group.
|
||||
// If any project has empty regions ("Вся РФ"), the whole group becomes "Вся РФ".
|
||||
if (! $groups[$key]['has_all_russia']) {
|
||||
$projectRegions = array_map('intval', (array) ($project->regions ?? []));
|
||||
if ($projectRegions === []) {
|
||||
$groups[$key]['has_all_russia'] = true;
|
||||
$groups[$key]['merged_regions'] = [];
|
||||
} else {
|
||||
$groups[$key]['merged_regions'] = array_values(array_unique(
|
||||
array_merge($groups[$key]['merged_regions'], $projectRegions)
|
||||
));
|
||||
}
|
||||
}
|
||||
$groups[$key]['projects'][] = $project;
|
||||
}
|
||||
|
||||
// 3. Sync each group
|
||||
foreach ($groups as $group) {
|
||||
if (now()->timezone('Europe/Moscow')->format('H:i') >= self::TIME_BUDGET_CUTOFF) {
|
||||
Log::warning('supplier.sync.time_budget_reached', [
|
||||
'processed_until' => $sp->id,
|
||||
'group' => $group['identifier'],
|
||||
]);
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->syncOne($sp, $client);
|
||||
$this->syncGroup($group);
|
||||
$consecutiveTransient = 0;
|
||||
} catch (TierEscalatedException $e) {
|
||||
Log::info("SyncSupplierProjectsJob: group {$group['identifier']} escalated to manual queue #{$e->queueRowId}, reason: {$e->reason}");
|
||||
|
||||
continue;
|
||||
} catch (WindowDeferredException) {
|
||||
Log::info("SyncSupplierProjectsJob: group {$group['identifier']} deferred by portal window");
|
||||
|
||||
continue;
|
||||
} catch (SupplierAuthException $e) {
|
||||
Mail::to((string) config('services.supplier.alert_email'))
|
||||
->queue(new SupplierCriticalAlertMail(
|
||||
@@ -94,7 +160,7 @@ class SyncSupplierProjectsJob implements ShouldQueue
|
||||
throw $e;
|
||||
} catch (SupplierTransientException $e) {
|
||||
$consecutiveTransient++;
|
||||
$this->logSyncFailure($sp, $e);
|
||||
$this->logGroupFailure($group, $e);
|
||||
if ($consecutiveTransient >= self::MASS_FAIL_THRESHOLD) {
|
||||
Mail::to((string) config('services.supplier.alert_email'))
|
||||
->queue(new SupplierCriticalAlertMail(
|
||||
@@ -107,7 +173,7 @@ class SyncSupplierProjectsJob implements ShouldQueue
|
||||
|
||||
continue;
|
||||
} catch (SupplierClientException $e) {
|
||||
$this->logSyncFailure($sp, $e);
|
||||
$this->logGroupFailure($group, $e);
|
||||
report($e);
|
||||
|
||||
continue;
|
||||
@@ -115,123 +181,239 @@ class SyncSupplierProjectsJob implements ShouldQueue
|
||||
}
|
||||
}
|
||||
|
||||
private function syncOne(SupplierProject $sp, SupplierPortalClient $client): void
|
||||
/**
|
||||
* @param array{signal_type: string, identifier: string, merged_regions: list<int>, has_all_russia: bool, platforms: list<string>, projects: list<Project>} $group
|
||||
*/
|
||||
private function syncGroup(array $group): void
|
||||
{
|
||||
$fkColumn = $this->fkColumnForPlatform($sp->platform);
|
||||
$signalType = $group['signal_type'];
|
||||
$identifier = $group['identifier'];
|
||||
$platforms = $group['platforms'];
|
||||
|
||||
/** @var EloquentCollection<int, Project> $liderraProjects */
|
||||
$liderraProjects = Project::on(self::DB_CONNECTION)
|
||||
->where($fkColumn, $sp->id)
|
||||
->where('is_active', true)
|
||||
/** @var list<Project> $groupProjects */
|
||||
$groupProjects = $group['projects'];
|
||||
|
||||
// Eligible-today: workday-mask for tomorrow
|
||||
$targetDate = Carbon::tomorrow('Europe/Moscow');
|
||||
$targetWeekday = $targetDate->isoWeekday();
|
||||
|
||||
/** @var list<Project> $eligible */
|
||||
$eligible = array_values(array_filter(
|
||||
$groupProjects,
|
||||
fn (Project $p) => ($p->delivery_days_mask & (1 << ($targetWeekday - 1))) !== 0
|
||||
));
|
||||
|
||||
if ($eligible === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Compute order and union workdays
|
||||
$eligibleLimits = array_map(fn (Project $p) => (int) $p->daily_limit_target, $eligible);
|
||||
$order = SupplierQuotaAllocator::computeOrder($eligibleLimits);
|
||||
|
||||
$workdaysUnion = [];
|
||||
foreach ($eligible as $p) {
|
||||
foreach ($this->bitmaskToList((int) $p->delivery_days_mask, 7) as $d) {
|
||||
$workdaysUnion[$d] = $d;
|
||||
}
|
||||
}
|
||||
sort($workdaysUnion);
|
||||
$workdays = $workdaysUnion;
|
||||
|
||||
// Portal constraint: one identifier = one B1/B2/B3 group — pass all regions as a single list.
|
||||
$allRegions = $group['merged_regions'];
|
||||
sort($allRegions);
|
||||
// count=0 → all-Russia; count=1 → named region; count>1 → merged → 'РФ'
|
||||
$tag = count($allRegions) === 1
|
||||
? (RussianRegions::CODE_TO_NAME[$allRegions[0]] ?? (string) $allRegions[0])
|
||||
: 'РФ';
|
||||
|
||||
// Find existing supplier_projects for this group (no subject_code filter)
|
||||
$existingSps = SupplierProject::on(self::DB_CONNECTION)
|
||||
->where('unique_key', $identifier)
|
||||
->where('signal_type', $signalType)
|
||||
->whereIn('platform', $platforms)
|
||||
->get();
|
||||
|
||||
if ($liderraProjects->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
if ($existingSps->isEmpty()) {
|
||||
// Create path: saveProjectMultiFlag → [platform => external_id]
|
||||
$dto = new SupplierProjectDto(
|
||||
platform: $platforms[0],
|
||||
signalType: $signalType,
|
||||
uniqueKey: $identifier,
|
||||
limit: $order,
|
||||
workdays: $workdays,
|
||||
regions: $allRegions,
|
||||
regionsReverse: false,
|
||||
status: 'active',
|
||||
tag: $tag,
|
||||
platforms: $platforms,
|
||||
);
|
||||
|
||||
$adapted = $this->adaptProjectsForAllocator($liderraProjects);
|
||||
$idMap = $this->client->saveProjectMultiFlag($dto);
|
||||
|
||||
$allocation = SupplierQuotaAllocator::allocate(
|
||||
platform: $sp->platform,
|
||||
signalType: $sp->signal_type,
|
||||
uniqueKey: $sp->unique_key,
|
||||
activeLiderraProjects: $adapted,
|
||||
targetDate: Carbon::tomorrow('Europe/Moscow'),
|
||||
);
|
||||
// Upsert supplier_projects rows (one per platform)
|
||||
foreach ($platforms as $platform) {
|
||||
$externalId = $idMap[$platform] ?? null;
|
||||
if ($externalId === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($allocation === null) {
|
||||
return;
|
||||
}
|
||||
$sp = SupplierProject::on(self::DB_CONNECTION)->forceCreate([
|
||||
'platform' => $platform,
|
||||
'signal_type' => $signalType,
|
||||
'unique_key' => $identifier,
|
||||
'subject_code' => null,
|
||||
'supplier_external_id' => (string) $externalId,
|
||||
'current_limit' => $order,
|
||||
'current_workdays' => $workdays,
|
||||
'current_regions' => $allRegions,
|
||||
'sync_status' => 'ok',
|
||||
'last_synced_at' => now(),
|
||||
]);
|
||||
|
||||
$current = SupplierProjectDto::fromModel($sp);
|
||||
if ($allocation->equals($current)) {
|
||||
return;
|
||||
}
|
||||
SupplierSyncLog::on(self::DB_CONNECTION)->create([
|
||||
'supplier_project_id' => $sp->id,
|
||||
'action' => 'create',
|
||||
'http_status' => 200,
|
||||
'created_at' => now(),
|
||||
]);
|
||||
|
||||
$isCreate = $sp->supplier_external_id === null;
|
||||
|
||||
// NOTE: НЕ оборачиваем в DB::transaction() — HTTP-call к supplier выходит за
|
||||
// границы транзакционного контекста, атомарности всё равно нет. Два DB-write
|
||||
// (supplier_project update + supplier_sync_log insert) на одной connection
|
||||
// выполняются последовательно; ошибка между ними — recoverable through retry
|
||||
// на следующем cron-tick'е (supplier_external_id уже записан, скип через equals()).
|
||||
if ($isCreate) {
|
||||
$externalId = $client->saveProject($allocation);
|
||||
$sp->forceFill([
|
||||
'supplier_external_id' => (string) $externalId,
|
||||
'current_limit' => $allocation->limit,
|
||||
'current_workdays' => $allocation->workdays,
|
||||
'current_regions' => $allocation->regions,
|
||||
'sync_status' => 'ok',
|
||||
'last_synced_at' => now(),
|
||||
])->save();
|
||||
$existingSps->push($sp);
|
||||
}
|
||||
} else {
|
||||
$client->updateProject((int) $sp->supplier_external_id, $allocation);
|
||||
$sp->forceFill([
|
||||
'current_limit' => $allocation->limit,
|
||||
'current_workdays' => $allocation->workdays,
|
||||
'current_regions' => $allocation->regions,
|
||||
'sync_status' => 'ok',
|
||||
'last_synced_at' => now(),
|
||||
])->save();
|
||||
// Fix #3 (review-followup): partial-set recovery — если предыдущий run создал
|
||||
// не все platforms (e.g. B1+B2 OK, B3 escalated), re-attempt missing via multi-flag
|
||||
// save с platforms=$missingPlatforms. Throws пропагируют в outer handle() catch
|
||||
// (SupplierAuth/Transient/Client) — full failover-counter semantics сохраняется.
|
||||
$existingPlatforms = $existingSps->pluck('platform')->all();
|
||||
$missingPlatforms = array_values(array_diff($platforms, $existingPlatforms));
|
||||
|
||||
if ($missingPlatforms !== []) {
|
||||
$missingDto = new SupplierProjectDto(
|
||||
platform: $missingPlatforms[0],
|
||||
signalType: $signalType,
|
||||
uniqueKey: $identifier,
|
||||
limit: $order,
|
||||
workdays: $workdays,
|
||||
regions: $allRegions,
|
||||
regionsReverse: false,
|
||||
status: 'active',
|
||||
tag: $tag,
|
||||
platforms: $missingPlatforms,
|
||||
);
|
||||
|
||||
$missingIdMap = $this->client->saveProjectMultiFlag($missingDto);
|
||||
|
||||
foreach ($missingPlatforms as $platform) {
|
||||
$externalId = $missingIdMap[$platform] ?? null;
|
||||
if ($externalId === null) {
|
||||
continue;
|
||||
}
|
||||
$sp = SupplierProject::on(self::DB_CONNECTION)->forceCreate([
|
||||
'platform' => $platform,
|
||||
'signal_type' => $signalType,
|
||||
'unique_key' => $identifier,
|
||||
'subject_code' => null,
|
||||
'supplier_external_id' => (string) $externalId,
|
||||
'current_limit' => $order,
|
||||
'current_workdays' => $workdays,
|
||||
'current_regions' => $allRegions,
|
||||
'sync_status' => 'ok',
|
||||
'last_synced_at' => now(),
|
||||
]);
|
||||
SupplierSyncLog::on(self::DB_CONNECTION)->create([
|
||||
'supplier_project_id' => $sp->id,
|
||||
'action' => 'create',
|
||||
'http_status' => 200,
|
||||
'created_at' => now(),
|
||||
]);
|
||||
$existingSps->push($sp);
|
||||
}
|
||||
}
|
||||
|
||||
// Fix #2 (review-followup): per-platform DTO в update-loop, чтобы portal получал
|
||||
// правильные srcrt/srcbl/srcmt для конкретной редактируемой строки (не first()
|
||||
// из mixed-platform existing set). R6 one shared limit/regions сохраняется.
|
||||
foreach ($existingSps as $sp) {
|
||||
if ($sp->supplier_external_id === null) {
|
||||
continue;
|
||||
}
|
||||
$perPlatformDto = new SupplierProjectDto(
|
||||
platform: $sp->platform,
|
||||
signalType: $signalType,
|
||||
uniqueKey: $identifier,
|
||||
limit: $order,
|
||||
workdays: $workdays,
|
||||
regions: $allRegions,
|
||||
regionsReverse: false,
|
||||
status: 'active',
|
||||
tag: $tag,
|
||||
platforms: [$sp->platform],
|
||||
);
|
||||
$this->channel->updateProject((int) $sp->supplier_external_id, $perPlatformDto);
|
||||
$sp->forceFill([
|
||||
'current_limit' => $order,
|
||||
'current_workdays' => $workdays,
|
||||
'current_regions' => $allRegions,
|
||||
'sync_status' => 'ok',
|
||||
'last_synced_at' => now(),
|
||||
])->save();
|
||||
|
||||
SupplierSyncLog::on(self::DB_CONNECTION)->create([
|
||||
'supplier_project_id' => $sp->id,
|
||||
'action' => 'update',
|
||||
'http_status' => 200,
|
||||
'created_at' => now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
SupplierSyncLog::on(self::DB_CONNECTION)->create([
|
||||
'supplier_project_id' => $sp->id,
|
||||
'action' => $isCreate ? 'create' : 'update',
|
||||
'http_status' => 200,
|
||||
'created_at' => now(),
|
||||
]);
|
||||
// Pivot: for each contributing Лидерра-project × each supplier_project → ON CONFLICT DO NOTHING
|
||||
foreach ($groupProjects as $lp) {
|
||||
foreach ($existingSps as $sp) {
|
||||
DB::connection(self::DB_CONNECTION)->table('project_supplier_links')->insertOrIgnore([
|
||||
'project_id' => $lp->id,
|
||||
'supplier_project_id' => $sp->id,
|
||||
'platform' => $sp->platform,
|
||||
'subject_code' => null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function logSyncFailure(SupplierProject $sp, Throwable $e): void
|
||||
/**
|
||||
* Log failure for a group (before any supplier_project is created/updated we don't have sp id,
|
||||
* so we look up existing or skip — best-effort audit).
|
||||
*
|
||||
* @param array{signal_type: string, identifier: string, merged_regions: list<int>, has_all_russia: bool, platforms: list<string>, projects: list<Project>} $group
|
||||
*/
|
||||
private function logGroupFailure(array $group, Throwable $e): void
|
||||
{
|
||||
$httpStatus = null;
|
||||
if ($e instanceof SupplierException) {
|
||||
$httpStatus = $e->httpStatus;
|
||||
}
|
||||
|
||||
SupplierSyncLog::on(self::DB_CONNECTION)->create([
|
||||
'supplier_project_id' => $sp->id,
|
||||
'action' => $sp->supplier_external_id === null ? 'create' : 'update',
|
||||
'http_status' => $httpStatus,
|
||||
'error_message' => substr($e->getMessage(), 0, 1000),
|
||||
'created_at' => now(),
|
||||
]);
|
||||
// Find any existing sp row for the group to link log entry (no subject_code filter)
|
||||
$sp = SupplierProject::on(self::DB_CONNECTION)
|
||||
->where('unique_key', $group['identifier'])
|
||||
->where('signal_type', $group['signal_type'])
|
||||
->first();
|
||||
|
||||
if ($sp !== null) {
|
||||
SupplierSyncLog::on(self::DB_CONNECTION)->create([
|
||||
'supplier_project_id' => $sp->id,
|
||||
'action' => $sp->supplier_external_id === null ? 'create' : 'update',
|
||||
'http_status' => $httpStatus,
|
||||
'error_message' => substr($e->getMessage(), 0, 1000),
|
||||
'created_at' => now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Адаптер Eloquent Project → stdClass с полями daily_limit/workdays/regions,
|
||||
* которые ожидает SupplierQuotaAllocator (pure function, не вяжется к Eloquent).
|
||||
*
|
||||
* Маппинг:
|
||||
* daily_limit ← daily_limit_target
|
||||
* workdays ← биты delivery_days_mask (bit 0=Пн, …, bit 6=Вс) → ISO 1..7
|
||||
* regions ← биты region_mask (bit 0=Центральный, …, bit 7=Дальневосточный) → 1..8
|
||||
*
|
||||
* @param EloquentCollection<int, Project> $projects
|
||||
* @return Collection<int, stdClass>
|
||||
*/
|
||||
private function adaptProjectsForAllocator(EloquentCollection $projects): Collection
|
||||
{
|
||||
return $projects->map(function (Project $p): stdClass {
|
||||
$obj = new stdClass;
|
||||
$obj->daily_limit = (int) $p->daily_limit_target;
|
||||
$obj->workdays = $this->bitmaskToList((int) $p->delivery_days_mask, 7);
|
||||
|
||||
// region_mask=255 (все 8 ФО, default) — catch-all семантика → пустой массив
|
||||
// у supplier ("без региональных ограничений"). Иначе — список выставленных битов.
|
||||
$regionMask = (int) $p->region_mask;
|
||||
$obj->regions = $regionMask === 255
|
||||
? []
|
||||
: $this->bitmaskToList($regionMask, 8);
|
||||
|
||||
return $obj;
|
||||
})->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* Bitmask → ordered list 1..maxBits для bits, выставленных в 1.
|
||||
* Bitmask → ordered list 1..maxBits.
|
||||
*
|
||||
* @return array<int, int>
|
||||
*/
|
||||
@@ -246,14 +428,4 @@ class SyncSupplierProjectsJob implements ShouldQueue
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
private function fkColumnForPlatform(string $platform): string
|
||||
{
|
||||
return match ($platform) {
|
||||
'B1' => 'supplier_b1_project_id',
|
||||
'B2' => 'supplier_b2_project_id',
|
||||
'B3' => 'supplier_b3_project_id',
|
||||
default => throw new \InvalidArgumentException("Unknown supplier platform: {$platform}"),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,28 +5,51 @@ declare(strict_types=1);
|
||||
namespace App\Jobs;
|
||||
|
||||
use App\Models\Project;
|
||||
use App\Models\SupplierProject;
|
||||
use App\Services\Supplier\Channel\Exceptions\TierEscalatedException;
|
||||
use App\Services\Supplier\Channel\Exceptions\WindowDeferredException;
|
||||
use App\Services\Supplier\Channel\FailoverProjectChannel;
|
||||
use App\Services\Supplier\Channel\SupplierProjectChannel;
|
||||
use App\Services\Supplier\Dto\SupplierProjectDto;
|
||||
use App\Services\Supplier\SupplierExportMode;
|
||||
use App\Services\Supplier\SupplierPortalClient;
|
||||
use App\Services\Supplier\SupplierProjectGrouping;
|
||||
use App\Support\RussianRegions;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Синхронизирует Лидерра-проект с supplier_projects на B1/B2/B3
|
||||
* в зависимости от signal_type.
|
||||
* в зависимости от signal_type и текущего SupplierExportMode.
|
||||
*
|
||||
* Семантика:
|
||||
* site / call → B1 + B2 + B3
|
||||
* sms с keyword → B2 + B3
|
||||
* sms без keyword → B3
|
||||
* Режимы:
|
||||
* online → для каждой (subject × platform-set) группы проекта:
|
||||
* saveProjectMultiFlag с полными параметрами (limit, regions, tag)
|
||||
* → upsert supplier_projects + pivot project_supplier_links.
|
||||
* batch → «каркас»: создаёт supplier_projects с limit=0, без регионов
|
||||
* (старый путь); ночной SyncSupplierProjectsJob дольёт полные параметры.
|
||||
*
|
||||
* Записывает полученные supplier_projects.id в projects.supplier_b{1,2,3}_project_id.
|
||||
* Канал миграции:
|
||||
* batch mode — SupplierProjectChannel (FailoverProjectChannel: ярус 1 AJAX
|
||||
* → ярус 2 browser-form → ярус 3 manual queue) для createProject.
|
||||
* online mode — multi-flag save идёт напрямую через SupplierPortalClient
|
||||
* (tier-1 AJAX only — multi-flag нет в tier-2 form по архитектуре
|
||||
* портала). При любом transient/auth fail → log warning + skip
|
||||
* subject; Laravel retry (tries=3 backoff [15s,60s,300s]) → ночной
|
||||
* SyncSupplierProjectsJob подберёт с полным failover каналом.
|
||||
* updateProject в online остаётся через $channel (полная схема failover).
|
||||
* При эскалации на ярус 3 / переносе по окну портала — platform/subject пропускается
|
||||
* (FK/pivot остаётся пустым; ночной SyncSupplierProjectsJob восстанавливает).
|
||||
*
|
||||
* Retry: 3 попытки с backoff [15s, 60s, 300s].
|
||||
*
|
||||
* Spec: docs/superpowers/plans/2026-05-11-plan5-frontend-projects-ui-plan.md Task 4
|
||||
* Spec: docs/superpowers/specs/2026-05-19-supplier-project-channel-failover-design.md §5
|
||||
* Plan: docs/superpowers/plans/2026-05-20-project-migration-redesign-plan-3-export.md Task 6
|
||||
*/
|
||||
class SyncSupplierProjectJob implements ShouldQueue
|
||||
{
|
||||
@@ -39,7 +62,7 @@ class SyncSupplierProjectJob implements ShouldQueue
|
||||
|
||||
public function __construct(public int $projectId) {}
|
||||
|
||||
public function handle(SupplierPortalClient $client): void
|
||||
public function handle(SupplierProjectChannel $channel): void
|
||||
{
|
||||
$project = Project::find($this->projectId);
|
||||
|
||||
@@ -49,57 +72,274 @@ class SyncSupplierProjectJob implements ShouldQueue
|
||||
return;
|
||||
}
|
||||
|
||||
$platforms = $this->resolvePlatforms($project);
|
||||
if (SupplierExportMode::isOnline()) {
|
||||
$this->handleOnline($project, $channel);
|
||||
} else {
|
||||
$this->handleBatch($project, $channel);
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Online mode: per-subject full-param sync
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private function handleOnline(Project $project, SupplierProjectChannel $channel): void
|
||||
{
|
||||
$client = app(SupplierPortalClient::class);
|
||||
|
||||
$platforms = SupplierProjectGrouping::resolvePlatforms($project);
|
||||
if ($platforms === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$identifier = SupplierProjectGrouping::buildUniqueKey($project, $platforms[0]);
|
||||
|
||||
// Portal constraint: one identifier = one B1/B2/B3 group (status=Doubles on duplicate name).
|
||||
// Pass all project regions as a single group — no per-subject split.
|
||||
$allRegions = array_map('intval', (array) ($project->regions ?? []));
|
||||
// count=0 → all-Russia; count=1 → named region; count>1 → merged → 'РФ'
|
||||
$tag = count($allRegions) === 1
|
||||
? (RussianRegions::CODE_TO_NAME[$allRegions[0]] ?? (string) $allRegions[0])
|
||||
: 'РФ';
|
||||
|
||||
$workdays = $this->workdaysFromMask((int) $project->delivery_days_mask);
|
||||
|
||||
// Idempotency: find existing by identifier regardless of subject_code (any previous run).
|
||||
$existingSps = SupplierProject::query()
|
||||
->where('unique_key', $identifier)
|
||||
->where('signal_type', (string) $project->signal_type)
|
||||
->whereIn('platform', $platforms)
|
||||
->get();
|
||||
|
||||
if ($existingSps->isEmpty()) {
|
||||
// Create path: saveProjectMultiFlag → [platform => external_id]
|
||||
$dto = new SupplierProjectDto(
|
||||
platform: $platforms[0],
|
||||
signalType: (string) $project->signal_type,
|
||||
uniqueKey: $identifier,
|
||||
limit: (int) $project->daily_limit_target,
|
||||
workdays: $workdays,
|
||||
regions: $allRegions,
|
||||
regionsReverse: false,
|
||||
status: 'active',
|
||||
tag: $tag,
|
||||
platforms: $platforms,
|
||||
);
|
||||
|
||||
try {
|
||||
$idMap = $client->saveProjectMultiFlag($dto);
|
||||
} catch (TierEscalatedException $e) {
|
||||
Log::info("SyncSupplierProjectJob: project {$project->id} escalated to manual queue #{$e->queueRowId}");
|
||||
|
||||
return;
|
||||
} catch (WindowDeferredException) {
|
||||
Log::info("SyncSupplierProjectJob: project {$project->id} deferred by portal window");
|
||||
|
||||
return;
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning("SyncSupplierProjectJob: online multi-flag save failed for project {$project->id} (".get_class($e).'): '.$e->getMessage());
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($platforms as $platform) {
|
||||
$externalId = $idMap[$platform] ?? null;
|
||||
if ($externalId === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$sp = SupplierProject::create([
|
||||
'platform' => $platform,
|
||||
'signal_type' => (string) $project->signal_type,
|
||||
'unique_key' => $identifier,
|
||||
'subject_code' => null,
|
||||
'supplier_external_id' => (string) $externalId,
|
||||
'current_limit' => (int) $project->daily_limit_target,
|
||||
'current_workdays' => $workdays,
|
||||
'current_regions' => $allRegions,
|
||||
'sync_status' => 'ok',
|
||||
'last_synced_at' => now(),
|
||||
]);
|
||||
|
||||
$existingSps->push($sp);
|
||||
}
|
||||
} else {
|
||||
// Partial-set recovery: если предыдущий run создал не все platforms.
|
||||
$existingPlatforms = $existingSps->pluck('platform')->all();
|
||||
$missingPlatforms = array_values(array_diff($platforms, $existingPlatforms));
|
||||
|
||||
if ($missingPlatforms !== []) {
|
||||
$missingDto = new SupplierProjectDto(
|
||||
platform: $missingPlatforms[0],
|
||||
signalType: (string) $project->signal_type,
|
||||
uniqueKey: $identifier,
|
||||
limit: (int) $project->daily_limit_target,
|
||||
workdays: $workdays,
|
||||
regions: $allRegions,
|
||||
regionsReverse: false,
|
||||
status: 'active',
|
||||
tag: $tag,
|
||||
platforms: $missingPlatforms,
|
||||
);
|
||||
|
||||
try {
|
||||
$missingIdMap = $client->saveProjectMultiFlag($missingDto);
|
||||
} catch (TierEscalatedException $e) {
|
||||
Log::info("SyncSupplierProjectJob: project {$project->id} missing-platform re-attempt escalated #{$e->queueRowId}");
|
||||
$missingIdMap = [];
|
||||
} catch (WindowDeferredException) {
|
||||
Log::info("SyncSupplierProjectJob: project {$project->id} missing-platform deferred by portal window");
|
||||
$missingIdMap = [];
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning("SyncSupplierProjectJob: missing-platform multi-flag failed for project {$project->id}: ".$e->getMessage());
|
||||
$missingIdMap = [];
|
||||
}
|
||||
|
||||
foreach ($missingPlatforms as $platform) {
|
||||
$externalId = $missingIdMap[$platform] ?? null;
|
||||
if ($externalId === null) {
|
||||
continue;
|
||||
}
|
||||
$sp = SupplierProject::create([
|
||||
'platform' => $platform,
|
||||
'signal_type' => (string) $project->signal_type,
|
||||
'unique_key' => $identifier,
|
||||
'subject_code' => null,
|
||||
'supplier_external_id' => (string) $externalId,
|
||||
'current_limit' => (int) $project->daily_limit_target,
|
||||
'current_workdays' => $workdays,
|
||||
'current_regions' => $allRegions,
|
||||
'sync_status' => 'ok',
|
||||
'last_synced_at' => now(),
|
||||
]);
|
||||
$existingSps->push($sp);
|
||||
}
|
||||
}
|
||||
|
||||
// Update existing supplier projects with current regions/limit.
|
||||
foreach ($existingSps as $sp) {
|
||||
if ($sp->supplier_external_id === null) {
|
||||
continue;
|
||||
}
|
||||
$perPlatformDto = new SupplierProjectDto(
|
||||
platform: $sp->platform,
|
||||
signalType: (string) $project->signal_type,
|
||||
uniqueKey: $identifier,
|
||||
limit: (int) $project->daily_limit_target,
|
||||
workdays: $workdays,
|
||||
regions: $allRegions,
|
||||
regionsReverse: false,
|
||||
status: 'active',
|
||||
tag: $tag,
|
||||
platforms: [$sp->platform],
|
||||
);
|
||||
$channel->updateProject((int) $sp->supplier_external_id, $perPlatformDto);
|
||||
$sp->forceFill([
|
||||
'current_limit' => (int) $project->daily_limit_target,
|
||||
'current_workdays' => $workdays,
|
||||
'current_regions' => $allRegions,
|
||||
'sync_status' => 'ok',
|
||||
'last_synced_at' => now(),
|
||||
])->save();
|
||||
}
|
||||
}
|
||||
|
||||
// Pivot: project × each supplier_project → ON CONFLICT DO NOTHING
|
||||
foreach ($existingSps as $sp) {
|
||||
DB::table('project_supplier_links')->insertOrIgnore([
|
||||
'project_id' => $project->id,
|
||||
'supplier_project_id' => $sp->id,
|
||||
'platform' => $sp->platform,
|
||||
'subject_code' => null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Batch mode: каркас (limit=0, no regions) — backward-compat
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private function handleBatch(Project $project, SupplierProjectChannel $channel): void
|
||||
{
|
||||
$platforms = SupplierProjectGrouping::resolvePlatforms($project);
|
||||
$workdays = $this->workdaysFromMask((int) $project->delivery_days_mask);
|
||||
|
||||
foreach ($platforms as $platform) {
|
||||
$uniqueKey = $this->buildUniqueKey($project, $platform);
|
||||
$supplierProjectId = $client->ensureSupplierProject($platform, $project->signal_type, $uniqueKey);
|
||||
$uniqueKey = SupplierProjectGrouping::buildUniqueKey($project, $platform);
|
||||
$column = 'supplier_'.strtolower($platform).'_project_id';
|
||||
$project->{$column} = $supplierProjectId;
|
||||
|
||||
// Idempotency: local supplier_projects-запись уже есть?
|
||||
$existing = SupplierProject::query()
|
||||
->where('platform', $platform)
|
||||
->where('signal_type', $project->signal_type)
|
||||
->where('unique_key', $uniqueKey)
|
||||
->first();
|
||||
|
||||
if ($existing !== null) {
|
||||
$project->{$column} = $existing->id;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$dto = new SupplierProjectDto(
|
||||
platform: $platform,
|
||||
signalType: (string) $project->signal_type,
|
||||
uniqueKey: $uniqueKey,
|
||||
limit: 0,
|
||||
workdays: $workdays,
|
||||
regions: [],
|
||||
regionsReverse: false,
|
||||
status: 'active',
|
||||
);
|
||||
|
||||
try {
|
||||
$externalId = $channel instanceof FailoverProjectChannel
|
||||
? $channel->createProjectForLiderra($project, $dto)
|
||||
: $channel->createProject($dto);
|
||||
} catch (TierEscalatedException $e) {
|
||||
Log::info("SyncSupplierProjectJob: project {$project->id} {$platform} escalated to manual queue #{$e->queueRowId}");
|
||||
|
||||
continue;
|
||||
} catch (WindowDeferredException) {
|
||||
Log::info("SyncSupplierProjectJob: project {$project->id} {$platform} deferred by portal window");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$sp = SupplierProject::query()->create([
|
||||
'platform' => $platform,
|
||||
'signal_type' => $project->signal_type,
|
||||
'unique_key' => $uniqueKey,
|
||||
'supplier_external_id' => (string) $externalId,
|
||||
'current_limit' => 0,
|
||||
'current_workdays' => $workdays,
|
||||
'current_regions' => null,
|
||||
'sync_status' => 'ok',
|
||||
]);
|
||||
|
||||
$project->{$column} = $sp->id;
|
||||
}
|
||||
|
||||
$project->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает список uppercase platform-кодов для данного project.
|
||||
* Коды соответствуют CHECK constraint: 'B1' / 'B2' / 'B3'.
|
||||
* Bitmask → ISO weekday list. bit 0 = Mon (ISO 1) … bit 6 = Sun (ISO 7).
|
||||
*
|
||||
* @return array<int, string>
|
||||
* Mirror of SyncSupplierProjectsJob::bitmaskToList(). Kept inline (not
|
||||
* extracted to a shared helper) to keep this fix surgical.
|
||||
*
|
||||
* @return list<int>
|
||||
*/
|
||||
private function resolvePlatforms(Project $project): array
|
||||
private function workdaysFromMask(int $mask): array
|
||||
{
|
||||
if (in_array($project->signal_type, ['site', 'call'], true)) {
|
||||
return ['B1', 'B2', 'B3'];
|
||||
$out = [];
|
||||
for ($i = 0; $i < 7; $i++) {
|
||||
if (($mask & (1 << $i)) !== 0) {
|
||||
$out[] = $i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
if ($project->signal_type === 'sms') {
|
||||
return $project->sms_keyword ? ['B2', 'B3'] : ['B3'];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Строит unique_key для пары (project, platform):
|
||||
* site/call → signal_identifier (домен / телефон)
|
||||
* sms B2 → sender + '+' + keyword
|
||||
* sms B3 → sender
|
||||
*/
|
||||
private function buildUniqueKey(Project $project, string $platform): string
|
||||
{
|
||||
if (in_array($project->signal_type, ['site', 'call'], true)) {
|
||||
return (string) $project->signal_identifier;
|
||||
}
|
||||
|
||||
// sms
|
||||
$sender = (string) ($project->sms_senders[0] ?? '');
|
||||
|
||||
if ($platform === 'B2') {
|
||||
return $sender.'+'.($project->sms_keyword ?? '');
|
||||
}
|
||||
|
||||
// B3
|
||||
return $sender;
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,6 +54,7 @@ class Deal extends Model
|
||||
'utm_campaign',
|
||||
'utm_content',
|
||||
'region_code',
|
||||
'subject_code',
|
||||
'city',
|
||||
'time_in_form_seconds',
|
||||
'lead_score',
|
||||
@@ -72,6 +73,7 @@ class Deal extends Model
|
||||
'duplicate_of_id' => 'integer',
|
||||
'escalated_count' => 'integer',
|
||||
'time_in_form_seconds' => 'integer',
|
||||
'subject_code' => 'integer',
|
||||
'lead_score' => 'decimal:2',
|
||||
'phones' => 'array',
|
||||
'is_test' => 'boolean',
|
||||
|
||||
@@ -4,12 +4,14 @@ declare(strict_types=1);
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Casts\PostgresIntArray;
|
||||
use Carbon\CarbonInterface;
|
||||
use Database\Factories\ProjectFactory;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
@@ -45,6 +47,9 @@ class Project extends Model
|
||||
'effective_limit_calculated_at',
|
||||
'region_mask',
|
||||
'region_mode',
|
||||
// Plan 6 (schema v8.20): Subject-level regions array (89 codes из resources/js/constants/regions.ts).
|
||||
// Источник истины с Plan 6+; region_mask/region_mode — DEPRECATED (Plan 6.5 cleanup).
|
||||
'regions',
|
||||
'delivery_days_mask',
|
||||
'assignment_strategy',
|
||||
'ttfr_target_minutes',
|
||||
@@ -69,6 +74,10 @@ class Project extends Model
|
||||
'daily_limit_target' => 'integer',
|
||||
'effective_daily_limit_today' => 'integer',
|
||||
'region_mask' => 'integer',
|
||||
// Plan 6: Subject-level regions array (89 codes). Используется кастомный
|
||||
// PostgresIntArray cast — Laravel stock 'array' посылает JSON `[1,2,3]`,
|
||||
// что Postgres отвергает на INT[] (ожидает literal `{1,2,3}`).
|
||||
'regions' => PostgresIntArray::class,
|
||||
'delivery_days_mask' => 'integer',
|
||||
'ttfr_target_minutes' => 'integer',
|
||||
'effective_limit_calculated_at' => 'datetime',
|
||||
@@ -107,6 +116,15 @@ class Project extends Model
|
||||
return $this->belongsTo(SupplierProject::class, 'supplier_b3_project_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsToMany<SupplierProject, $this>
|
||||
*/
|
||||
public function supplierProjects(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(SupplierProject::class, 'project_supplier_links')
|
||||
->withPivot(['platform', 'subject_code']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Активные проекты, у которых сегодняшний день включён в delivery_days_mask.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* Очередь яруса 3 резерва канала миграции проектов.
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-19-supplier-project-channel-failover-design.md §4.5
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $project_id
|
||||
* @property string $platform
|
||||
* @property string $operation
|
||||
* @property string|null $external_id
|
||||
* @property array<string, mixed> $payload_snapshot
|
||||
* @property string $failure_reason
|
||||
* @property string $status
|
||||
* @property int|null $resolved_by_user_id
|
||||
* @property Carbon|null $created_at
|
||||
* @property Carbon|null $resolved_at
|
||||
*/
|
||||
class SupplierManualSyncQueue extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'supplier_manual_sync_queue';
|
||||
|
||||
public $timestamps = false;
|
||||
|
||||
protected $fillable = [
|
||||
'project_id', 'platform', 'operation', 'external_id',
|
||||
'payload_snapshot', 'failure_reason', 'status',
|
||||
'resolved_by_user_id', 'created_at', 'resolved_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'payload_snapshot' => 'array',
|
||||
'created_at' => 'datetime',
|
||||
'resolved_at' => 'datetime',
|
||||
];
|
||||
|
||||
public function project(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Project::class);
|
||||
}
|
||||
|
||||
public function resolver(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'resolved_by_user_id');
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use Database\Factories\SupplierProjectFactory;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
|
||||
/**
|
||||
* Supplier-уровневый агрегат проекта у поставщика crm.bp-gr.ru.
|
||||
@@ -40,6 +41,7 @@ class SupplierProject extends Model
|
||||
'sync_status',
|
||||
'last_synced_at',
|
||||
'inactive_since',
|
||||
'subject_code',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
@@ -50,6 +52,7 @@ class SupplierProject extends Model
|
||||
'current_limit' => 'integer',
|
||||
'last_synced_at' => 'datetime',
|
||||
'inactive_since' => 'datetime',
|
||||
'subject_code' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -81,6 +84,15 @@ class SupplierProject extends Model
|
||||
return $query->where('signal_type', $signalType)->where('unique_key', $uniqueKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsToMany<Project, $this>
|
||||
*/
|
||||
public function projects(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Project::class, 'project_supplier_links')
|
||||
->withPivot(['platform', 'subject_code']);
|
||||
}
|
||||
|
||||
protected static function newFactory(): SupplierProjectFactory
|
||||
{
|
||||
return SupplierProjectFactory::new();
|
||||
|
||||
@@ -2,8 +2,13 @@
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Services\Supplier\Channel\AjaxProjectChannel;
|
||||
use App\Services\Supplier\Channel\FailoverProjectChannel;
|
||||
use App\Services\Supplier\Channel\FormProjectChannel;
|
||||
use App\Services\Supplier\Channel\SupplierProjectChannel;
|
||||
use App\Services\Supplier\ProcessFactory;
|
||||
use App\Services\Supplier\SymfonyProcessFactory;
|
||||
use Illuminate\Contracts\Mail\Mailer;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
@@ -17,6 +22,18 @@ class AppServiceProvider extends ServiceProvider
|
||||
ProcessFactory::class,
|
||||
SymfonyProcessFactory::class,
|
||||
);
|
||||
|
||||
// Резерв канала миграции проектов: SupplierProjectChannel резолвится в
|
||||
// декоратор-оркестратор (ярус 1 AJAX → ярус 2 browser-form → ярус 3 queue).
|
||||
// Spec: docs/superpowers/specs/2026-05-19-supplier-project-channel-failover-design.md §4.4
|
||||
$this->app->bind(
|
||||
SupplierProjectChannel::class,
|
||||
fn ($app) => new FailoverProjectChannel(
|
||||
$app->make(AjaxProjectChannel::class),
|
||||
$app->make(FormProjectChannel::class),
|
||||
$app->make(Mailer::class),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -105,7 +105,7 @@ final class HistoricalImportService
|
||||
}
|
||||
|
||||
/**
|
||||
* Маппит статус: каноническая таблица §6.4 → tenant-override → fallback 'new'.
|
||||
* Маппит статус: StatusRuToSlugMapper → tenant-override → fallback 'new'.
|
||||
* Неизвестный статус инкрементит счётчик в $unknown по ссылке.
|
||||
*
|
||||
* @param array<string, string> $overrides
|
||||
|
||||
@@ -5,29 +5,36 @@ declare(strict_types=1);
|
||||
namespace App\Services\Import;
|
||||
|
||||
/**
|
||||
* Маппинг русских названий статусов воронки в slug (ТЗ §6.4).
|
||||
* Маппинг русских названий статусов (старые 14 названий поставщика + новые 5)
|
||||
* в slug 5-статусной воронки (редизайн 2026-05-17).
|
||||
*
|
||||
* Чистый сервис без зависимостей. Tenant-специфичные переопределения
|
||||
* неизвестных статусов накладываются вызывающим кодом (HistoricalImportService).
|
||||
*/
|
||||
class StatusRuToSlugMapper
|
||||
{
|
||||
/** @var array<string, string> Канонический маппинг ТЗ §6.4 (14 статусов воронки). */
|
||||
/** @var array<string, string> Русские названия → 5 slug'ов воронки (редизайн 2026-05-17). */
|
||||
private const STATUS_RU_TO_SLUG = [
|
||||
'Новые' => 'new',
|
||||
// Новые названия 5-статусной воронки.
|
||||
'Новая сделка' => 'new',
|
||||
'Просмотрено' => 'viewed',
|
||||
'Проработан' => 'worked',
|
||||
'База' => 'base',
|
||||
'Недозвон' => 'missed',
|
||||
'Переговоры' => 'negotiations',
|
||||
'Ожидаем оплаты' => 'waiting_payment',
|
||||
'Партнерка' => 'partnership',
|
||||
'Оплачено' => 'paid',
|
||||
'Закрыто и не реализовано' => 'closed',
|
||||
'Тест драйв' => 'test_drive',
|
||||
'Горячий' => 'hot',
|
||||
'На замену' => 'replacement',
|
||||
'Конечный недозвон' => 'final_missed',
|
||||
'В работе' => 'in_progress',
|
||||
'Сделка' => 'won',
|
||||
'Не реализовано' => 'lost',
|
||||
// Старые 14 названий поставщика → новые slug'и (исторический CSV-импорт).
|
||||
'Новые' => 'new',
|
||||
'Проработан' => 'in_progress',
|
||||
'База' => 'in_progress',
|
||||
'Недозвон' => 'in_progress',
|
||||
'Переговоры' => 'in_progress',
|
||||
'Ожидаем оплаты' => 'in_progress',
|
||||
'Партнерка' => 'in_progress',
|
||||
'Оплачено' => 'won',
|
||||
'Закрыто и не реализовано' => 'lost',
|
||||
'Тест драйв' => 'in_progress',
|
||||
'Горячий' => 'in_progress',
|
||||
'На замену' => 'in_progress',
|
||||
'Конечный недозвон' => 'in_progress',
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -39,7 +46,8 @@ class StatusRuToSlugMapper
|
||||
}
|
||||
|
||||
/**
|
||||
* Полная каноническая таблица — для UI wizard'а (показать варианты).
|
||||
* Полная таблица соответствия: русское название → slug 5-статусной воронки
|
||||
* (18 ключей — старые и новые названия схлопываются в 5 slug'ов).
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Random\Randomizer;
|
||||
|
||||
/**
|
||||
* Отбор получателей входящего лида: ≤ CAP случайных из eligible (sharing cap).
|
||||
*
|
||||
* cap=3 — защита владельца номера-донора (лид продаётся максимум 3 раза).
|
||||
* Eligible уже отфильтрован LeadRouter (есть остаток лимита) → отбор лимит не
|
||||
* превышает. Рандом через инъектируемый \Random\Randomizer (тесты сидируют
|
||||
* Mt19937 для детерминизма; прод — CSPRNG по умолчанию).
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-20-project-migration-redesign-design.md §4.6.
|
||||
*/
|
||||
final class LeadDistributor
|
||||
{
|
||||
public const CAP = 3;
|
||||
|
||||
public function __construct(private readonly Randomizer $randomizer = new Randomizer) {}
|
||||
|
||||
/**
|
||||
* @template T
|
||||
*
|
||||
* @param Collection<int, T> $eligible
|
||||
* @return Collection<int, T>
|
||||
*/
|
||||
public function selectRecipients(Collection $eligible): Collection
|
||||
{
|
||||
$items = $eligible->values()->all();
|
||||
|
||||
if (count($items) <= self::CAP) {
|
||||
return collect($items);
|
||||
}
|
||||
|
||||
$keys = $this->randomizer->pickArrayKeys($items, self::CAP);
|
||||
|
||||
return collect($keys)->map(fn (int $k) => $items[$k])->values();
|
||||
}
|
||||
}
|
||||
@@ -8,70 +8,45 @@ use App\Models\Project;
|
||||
use App\Models\SupplierProject;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Подбор eligible Лидерра-проектов для входящего лида (sharing-model §6).
|
||||
*
|
||||
* Алгоритм:
|
||||
* 1. SELECT projects WHERE supplier_b{1,2,3}_project_id = $supplier->id (по platform).
|
||||
* 2. Фильтр: is_active=true.
|
||||
* 3. Workdays: (delivery_days_mask & today_bit) <> 0, today_bit = 1 << (ISO_DOW - 1).
|
||||
* 4. delivered_today < COALESCE(effective_daily_limit_today, daily_limit_target).
|
||||
* 5. tenants.balance_leads > 0 OR tenants.balance_rub > 0 (через WHERE EXISTS;
|
||||
* Plan 4 Task 4: dual-balance — rub-only tenant ДОЛЖЕН пройти, LedgerService
|
||||
* сам резолвит prepaid/rub и кидает InsufficientBalanceException, если оба = 0).
|
||||
* 6. Region match через PhonePrefixService::phoneMatchesRegions (в PHP, не в SQL —
|
||||
* district-bit резолвится по 3/4-значному коду в PHP-словаре).
|
||||
* 7. Сортировка: created_at ASC, id ASC (детерминированно — spec §6 step 4).
|
||||
* Eligibility — структурно через pivot project_supplier_links: проект eligible,
|
||||
* если связан с пришедшим supplier_project (= источник × субъект) + активен +
|
||||
* сегодня рабочий день + есть остаток лимита + у тенанта есть баланс.
|
||||
*
|
||||
* Plan 3 Task 3: запрос идёт через connection `pgsql_supplier` (BYPASSRLS-роль
|
||||
* crm_supplier_worker). Это закрывает WARN #2 — в sharing-flow tenant ещё не
|
||||
* определён, SELECT обходит RLS-фильтрацию и видит проекты ВСЕХ tenant'ов
|
||||
* параллельно. WHERE-фильтры (is_active, FK на supplier_project, workdays, лимиты,
|
||||
* balance) сохраняются как defense-in-depth.
|
||||
* Регион сопоставляется самим supplier_project (тег = субъект) — phone-prefix
|
||||
* фильтр убран (эпик миграции проектов, Q5): для мобильных он no-op, а регион
|
||||
* гарантирован тем, через какой supplier_project пришёл лид.
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-10-supplier-integration-design.md §6 +
|
||||
* docs/superpowers/specs/2026-05-11-plan3-supplier-sync-design.md §1.
|
||||
* Запрос через connection pgsql_supplier (BYPASSRLS crm_supplier_worker) — в
|
||||
* sharing-flow tenant ещё не определён, SELECT видит проекты всех tenant'ов.
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-20-project-migration-redesign-design.md §4.5.
|
||||
*/
|
||||
class LeadRouter
|
||||
{
|
||||
public function __construct(
|
||||
private readonly PhonePrefixService $phonePrefix,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Project>
|
||||
*/
|
||||
public function matchEligibleProjects(SupplierProject $supplierProject, string $phone): Collection
|
||||
public function matchEligibleProjects(SupplierProject $supplierProject): Collection
|
||||
{
|
||||
$fkColumn = match ($supplierProject->platform) {
|
||||
'B1' => 'supplier_b1_project_id',
|
||||
'B2' => 'supplier_b2_project_id',
|
||||
'B3' => 'supplier_b3_project_id',
|
||||
// Unreachable per CHECK chk_supplier_projects_platform; defensive for static analysis.
|
||||
default => throw new InvalidArgumentException(
|
||||
"Unknown supplier platform: {$supplierProject->platform}"
|
||||
),
|
||||
};
|
||||
|
||||
// МСК-aligned ISO day-of-week: Plan 2 Task 9 reset cron also runs at 00:00 МСК,
|
||||
// so workday-mask check must use same timezone to avoid off-by-one near midnight.
|
||||
// МСК-aligned ISO day-of-week (reset-cron тоже 00:00 МСК).
|
||||
$todayBit = 1 << (Carbon::now('Europe/Moscow')->isoWeekday() - 1);
|
||||
|
||||
/** @var Collection<int, Project> $candidates */
|
||||
$candidates = Project::on('pgsql_supplier')
|
||||
->where($fkColumn, $supplierProject->id)
|
||||
->whereExists(function ($q) use ($supplierProject): void {
|
||||
$q->selectRaw('1')
|
||||
->from('project_supplier_links')
|
||||
->whereColumn('project_supplier_links.project_id', 'projects.id')
|
||||
->where('project_supplier_links.supplier_project_id', $supplierProject->id);
|
||||
})
|
||||
->where('is_active', true)
|
||||
->whereRaw('(delivery_days_mask & ?) <> 0', [$todayBit])
|
||||
->whereRaw(
|
||||
'delivered_today < COALESCE(effective_daily_limit_today, daily_limit_target)'
|
||||
)
|
||||
->whereRaw('delivered_today < COALESCE(effective_daily_limit_today, daily_limit_target)')
|
||||
->whereExists(function ($q): void {
|
||||
// Plan 4 Task 4: dual-balance — допускаем rub-only tenant'ов.
|
||||
// LedgerService::chargeForDelivery сам выбирает prepaid (balance_leads--)
|
||||
// или rub (balance_rub -= tier_price) и кидает InsufficientBalanceException,
|
||||
// если ОБА = 0. До Plan 4 фильтр был строгий balance_leads > 0 (prepaid only).
|
||||
$q->selectRaw('1')
|
||||
->from('tenants')
|
||||
->whereColumn('tenants.id', 'projects.tenant_id')
|
||||
@@ -84,12 +59,6 @@ class LeadRouter
|
||||
->orderBy('id')
|
||||
->get();
|
||||
|
||||
return $candidates->filter(
|
||||
fn (Project $p): bool => $this->phonePrefix->phoneMatchesRegions(
|
||||
$phone,
|
||||
(int) $p->region_mask,
|
||||
(string) $p->region_mode,
|
||||
)
|
||||
)->values();
|
||||
return $candidates->values();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,8 +14,9 @@ class ProjectService
|
||||
public function update(Project $project, array $data): Project
|
||||
{
|
||||
// Immutable fields — silently drop (don't 422)
|
||||
// signal_identifier — теперь editable (18.05.2026 ux), валидируется в UpdateProjectRequest.
|
||||
unset(
|
||||
$data['tenant_id'], $data['signal_type'], $data['signal_identifier'],
|
||||
$data['tenant_id'], $data['signal_type'],
|
||||
$data['delivered_today'], $data['delivered_in_month'],
|
||||
$data['supplier_b1_project_id'], $data['supplier_b2_project_id'], $data['supplier_b3_project_id'],
|
||||
$data['archived_at'],
|
||||
@@ -31,7 +32,14 @@ class ProjectService
|
||||
], 422));
|
||||
}
|
||||
|
||||
$needsResync = array_key_exists('sms_senders', $data) || array_key_exists('sms_keyword', $data);
|
||||
// Resync на смену источник-несущих полей, регионов, лимита и дней недели —
|
||||
// поставщик должен видеть актуальные параметры сразу, не дожидаясь ночного батча.
|
||||
$needsResync = array_key_exists('sms_senders', $data)
|
||||
|| array_key_exists('sms_keyword', $data)
|
||||
|| array_key_exists('signal_identifier', $data)
|
||||
|| array_key_exists('regions', $data)
|
||||
|| array_key_exists('daily_limit_target', $data)
|
||||
|| array_key_exists('delivery_days_mask', $data);
|
||||
|
||||
$project->update($data);
|
||||
|
||||
@@ -114,15 +122,41 @@ class ProjectService
|
||||
return ['updated' => $updated, 'skipped' => [], 'warnings' => []];
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan 6.5: субъект-уровневый bulk-edit `regions` INT[].
|
||||
*
|
||||
* Для каждого проекта: regions := unique(regions ∪ add_regions) \ remove_regions,
|
||||
* отсортировано по возрастанию. `regions[]` — источник истины региональной
|
||||
* фильтрации с Plan 6 (outbound SyncSupplierProjectsJob читает именно его).
|
||||
* Legacy `region_mask` здесь не трогается — как и в одиночном PATCH
|
||||
* /api/projects/{id}; его удаление — Plan 6.5 cleanup.
|
||||
*
|
||||
* NB: проект с regions=[] («вся РФ») при add_regions сужается до выбранных
|
||||
* субъектов — это осознанное действие оператора bulk-диалога.
|
||||
*
|
||||
* Обновление идёт через model-инстанс (не query-builder mass update): каст
|
||||
* PostgresIntArray::set() сериализует PHP-массив в PG-литерал `{1,2,3}`, а
|
||||
* mass update каст не применяет. count ≤ BULK_MAX (500) — допустимо.
|
||||
*/
|
||||
private function bulkUpdateRegions($query, array $payload): array
|
||||
{
|
||||
$add = (int) ($payload['add'] ?? 0);
|
||||
$remove = (int) ($payload['remove'] ?? 0);
|
||||
$add = array_map('intval', $payload['add_regions'] ?? []);
|
||||
$remove = array_map('intval', $payload['remove_regions'] ?? []);
|
||||
|
||||
// region_mask = (region_mask | add) & ~remove, clamped to 8 bits (0–255)
|
||||
$updated = $query->update([
|
||||
'region_mask' => \DB::raw("(region_mask | {$add}) & ~{$remove} & 255"),
|
||||
]);
|
||||
if ($add === [] && $remove === []) {
|
||||
return ['updated' => 0, 'skipped' => [], 'warnings' => []];
|
||||
}
|
||||
|
||||
$projects = (clone $query)->get(['id', 'regions']);
|
||||
$updated = 0;
|
||||
|
||||
foreach ($projects as $project) {
|
||||
$next = array_values(array_unique([...($project->regions ?? []), ...$add]));
|
||||
$next = array_values(array_diff($next, $remove));
|
||||
sort($next);
|
||||
$project->update(['regions' => $next]);
|
||||
$updated++;
|
||||
}
|
||||
|
||||
return ['updated' => $updated, 'skipped' => [], 'warnings' => []];
|
||||
}
|
||||
@@ -191,6 +225,11 @@ class ProjectService
|
||||
|
||||
$data['tenant_id'] = $tenant->id;
|
||||
$data['is_active'] = true;
|
||||
$data['regions'] = $data['regions'] ?? [];
|
||||
// Plan 6 dual-write: regions[] источник истины; region_mask/mode — legacy для
|
||||
// PhonePrefixService / LeadRouter, удаляются в Plan 6.5 после переключения читателей.
|
||||
$data['region_mask'] = 255;
|
||||
$data['region_mode'] = 'include';
|
||||
$project = Project::create($data);
|
||||
|
||||
SyncSupplierProjectJob::dispatch($project->id);
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Support\RussianRegions;
|
||||
|
||||
/**
|
||||
* Резолвит регион-тег поставщика (raw_payload['tag'] = имя субъекта или «РФ»)
|
||||
* в код субъекта 1..89. «РФ»/пусто/неизвестно → null (пул «Вся РФ»/неизвестно).
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-20-project-migration-redesign-design.md §4.4.
|
||||
*/
|
||||
final class RegionTagResolver
|
||||
{
|
||||
public function resolve(string $tag): ?int
|
||||
{
|
||||
$tag = trim($tag);
|
||||
|
||||
if ($tag === '' || $tag === 'РФ') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return RussianRegions::nameToCode()[$tag] ?? null;
|
||||
}
|
||||
}
|
||||
@@ -12,8 +12,8 @@ use Illuminate\Support\Facades\DB;
|
||||
* managers_summary — агрегат сделок по менеджерам за период (audit F1).
|
||||
*
|
||||
* Группировка по deals.manager_id; неназначенные (manager_id IS NULL) сводятся
|
||||
* в строку «Не назначен». «Оплачено» = status='paid' (won-статус воронки, как
|
||||
* в DashboardController). Конверсия = paid / total * 100, округление до 0.1.
|
||||
* в строку «Не назначен». «Оплачено» = status='won' (won-статус воронки, как
|
||||
* в DashboardController). Конверсия = won / total * 100, округление до 0.1.
|
||||
*
|
||||
* parameters: date_from, date_to (Y-m-d). Исключаются soft-deleted
|
||||
* (deleted_at IS NULL) и тестовые (is_test=false) сделки. RLS-обёртка
|
||||
@@ -48,7 +48,7 @@ class ManagersSummaryProvider implements ReportDataProvider
|
||||
"deals.manager_id,
|
||||
users.first_name, users.last_name, users.email,
|
||||
COUNT(*) AS total,
|
||||
COUNT(*) FILTER (WHERE deals.status = 'paid') AS paid"
|
||||
COUNT(*) FILTER (WHERE deals.status = 'won') AS paid"
|
||||
)
|
||||
->get();
|
||||
|
||||
|
||||
@@ -12,8 +12,8 @@ use Illuminate\Support\Facades\DB;
|
||||
* sources_summary — агрегат сделок по источнику (utm_source) за период (audit F1).
|
||||
*
|
||||
* Группировка по deals.utm_source; сделки без метки (NULL/пусто) сводятся в
|
||||
* строку «Прямые / без метки». «Оплачено» = status='paid'. Конверсия =
|
||||
* paid / total * 100, округление до 0.1.
|
||||
* строку «Прямые / без метки». «Оплачено» = status='won'. Конверсия =
|
||||
* won / total * 100, округление до 0.1.
|
||||
*
|
||||
* parameters: date_from, date_to (Y-m-d). Исключаются soft-deleted и тестовые
|
||||
* сделки. RLS-обёртка SET LOCAL app.current_tenant_id — паттерн DealsExportProvider.
|
||||
@@ -45,7 +45,7 @@ class SourcesSummaryProvider implements ReportDataProvider
|
||||
->selectRaw(
|
||||
"utm_source,
|
||||
COUNT(*) AS total,
|
||||
COUNT(*) FILTER (WHERE status = 'paid') AS paid"
|
||||
COUNT(*) FILTER (WHERE status = 'won') AS paid"
|
||||
)
|
||||
->get();
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Supplier\Channel;
|
||||
|
||||
use App\Services\Supplier\Dto\SupplierProjectDto;
|
||||
use App\Services\Supplier\SupplierPortalClient;
|
||||
|
||||
/**
|
||||
* Ярус 1: тонкий адаптер над SupplierPortalClient (rt-project-* AJAX).
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-19-supplier-project-channel-failover-design.md §4.2
|
||||
*/
|
||||
final class AjaxProjectChannel implements SupplierProjectChannel
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SupplierPortalClient $client,
|
||||
) {}
|
||||
|
||||
public function createProject(SupplierProjectDto $dto): int
|
||||
{
|
||||
return $this->client->saveProject($dto);
|
||||
}
|
||||
|
||||
public function updateProject(int $externalId, SupplierProjectDto $dto): void
|
||||
{
|
||||
$this->client->updateProject($externalId, $dto);
|
||||
}
|
||||
|
||||
/**
|
||||
* Сырые rt-строки портала → контрактная форма SupplierProjectChannel.
|
||||
*
|
||||
* Портал не отдаёт platform/signal_type/unique_key напрямую. Маппинг
|
||||
* (verified live 2026-05-19, см. SupplierPortalClient::listProjects docblock):
|
||||
* - platform ← префикс name "B<n>_..." (B1/B2/B3); иначе null;
|
||||
* - signal_type ← type: hosts→site, calls→call, sms→sms;
|
||||
* - unique_key ← content (домен / телефон / sender).
|
||||
* Сырые поля остаются (id, tag, name, type, content, ...) — для дебага.
|
||||
*/
|
||||
public function listProjects(): array
|
||||
{
|
||||
$out = [];
|
||||
foreach ($this->client->listProjects() as $row) {
|
||||
if (! is_array($row)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = (string) ($row['name'] ?? '');
|
||||
$platform = preg_match('/^(B[123])_/', $name, $m) === 1 ? $m[1] : null;
|
||||
|
||||
$signalType = match ($row['type'] ?? null) {
|
||||
'hosts' => 'site',
|
||||
'calls' => 'call',
|
||||
'sms' => 'sms',
|
||||
default => null,
|
||||
};
|
||||
|
||||
$out[] = $row + [
|
||||
'platform' => $platform,
|
||||
'signal_type' => $signalType,
|
||||
'unique_key' => (string) ($row['content'] ?? ''),
|
||||
];
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Supplier\Channel\Exceptions;
|
||||
|
||||
/**
|
||||
* Брошен FailoverProjectChannel когда операция эскалирована на ярус 3.
|
||||
*
|
||||
* Job-уровень ловит и помечает текущую попытку как отложенную к ручному вмешательству.
|
||||
*
|
||||
* Spec §4.4 ("manual_required").
|
||||
*/
|
||||
final class TierEscalatedException extends \RuntimeException
|
||||
{
|
||||
public function __construct(
|
||||
public readonly int $queueRowId,
|
||||
public readonly string $reason,
|
||||
string $message = '',
|
||||
) {
|
||||
parent::__construct($message ?: "Escalated to manual queue (row #{$queueRowId}, reason: {$reason})");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Supplier\Channel\Exceptions;
|
||||
|
||||
/**
|
||||
* Маркер «портал отказал по причине окна редактирования» (22:00-00:00 МСК).
|
||||
*
|
||||
* НЕ сбой канала — операция переносится. FailoverProjectChannel пропускает
|
||||
* эскалацию ярусов и не пишет в supplier_manual_sync_queue. Job-уровень
|
||||
* получает исключение и помечает попытку как deferred.
|
||||
*
|
||||
* Spec §8.
|
||||
*/
|
||||
final class WindowDeferredException extends \RuntimeException {}
|
||||
@@ -0,0 +1,200 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Supplier\Channel;
|
||||
|
||||
use App\Exceptions\Supplier\SupplierAuthException;
|
||||
use App\Exceptions\Supplier\SupplierClientException;
|
||||
use App\Exceptions\Supplier\SupplierTransientException;
|
||||
use App\Mail\SupplierCriticalAlertMail;
|
||||
use App\Models\Project;
|
||||
use App\Models\SupplierManualSyncQueue;
|
||||
use App\Services\Supplier\Channel\Exceptions\TierEscalatedException;
|
||||
use App\Services\Supplier\Channel\Exceptions\WindowDeferredException;
|
||||
use App\Services\Supplier\Dto\SupplierProjectDto;
|
||||
use Illuminate\Contracts\Mail\Mailer;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Декоратор-оркестратор: ярус 1 (AJAX) → ярус 2 (form-driving) → ярус 3 (manual queue).
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-19-supplier-project-channel-failover-design.md §4.4
|
||||
*
|
||||
* Bridge-методы createProjectForLiderra/updateProjectForLiderra принимают Project
|
||||
* (нужен для project_id в очереди яруса 3). Прямые createProject/updateProject
|
||||
* сохраняются для интерфейс-совместимости (без эскалации).
|
||||
*/
|
||||
final class FailoverProjectChannel implements SupplierProjectChannel
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SupplierProjectChannel $tier1,
|
||||
private readonly SupplierProjectChannel $tier2,
|
||||
private readonly Mailer $mailer,
|
||||
) {}
|
||||
|
||||
public function createProject(SupplierProjectDto $dto): int
|
||||
{
|
||||
return $this->tier1->createProject($dto);
|
||||
}
|
||||
|
||||
public function updateProject(int $externalId, SupplierProjectDto $dto): void
|
||||
{
|
||||
$this->tier1->updateProject($externalId, $dto);
|
||||
}
|
||||
|
||||
public function listProjects(): array
|
||||
{
|
||||
return $this->tier1->listProjects();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create с эскалацией: использует Project для project_id в очереди яруса 3.
|
||||
*/
|
||||
public function createProjectForLiderra(Project $project, SupplierProjectDto $dto): int
|
||||
{
|
||||
// Spec §4.4 шаг 2: портальная сверка через listProjects() до любого create.
|
||||
// Защита от дубля при полу-успехе яруса 1 в прошлом запуске.
|
||||
try {
|
||||
$existing = $this->findOnPortal($dto);
|
||||
if ($existing !== null) {
|
||||
return $existing;
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
// listProjects недоступен — продолжаем (ярус-эскалация покроет сбой),
|
||||
// но провал дедупа логируем: иначе при полу-успехе яруса 1 в прошлом
|
||||
// прогоне молча создастся дубль rt-проекта.
|
||||
Log::warning('FailoverProjectChannel: dedup-сверка listProjects провалена', [
|
||||
'platform' => $dto->platform,
|
||||
'unique_key' => $dto->uniqueKey,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
|
||||
try {
|
||||
return $this->tier1->createProject($dto);
|
||||
} catch (WindowDeferredException $e) {
|
||||
throw $e;
|
||||
} catch (SupplierTransientException $e) {
|
||||
$this->escalateToTier3($project, 'create', null, $dto, 'portal_unreachable', $e);
|
||||
} catch (SupplierClientException|SupplierAuthException $e) {
|
||||
try {
|
||||
$id = $this->tier2->createProject($dto);
|
||||
$this->alertFailoverToForm($project, 'create', $e);
|
||||
|
||||
return $id;
|
||||
} catch (Throwable $tier2Error) {
|
||||
$this->escalateToTier3(
|
||||
$project, 'create', null, $dto,
|
||||
$this->classifyTier2Failure($tier2Error), $tier2Error,
|
||||
);
|
||||
}
|
||||
}
|
||||
// Все ветки выше терминируют (return / throw / escalateToTier3(): never) —
|
||||
// явный «unreachable»-throw не нужен (deadCode.unreachable).
|
||||
}
|
||||
|
||||
public function updateProjectForLiderra(Project $project, int $externalId, SupplierProjectDto $dto): void
|
||||
{
|
||||
try {
|
||||
$this->tier1->updateProject($externalId, $dto);
|
||||
|
||||
return;
|
||||
} catch (WindowDeferredException $e) {
|
||||
throw $e;
|
||||
} catch (SupplierTransientException $e) {
|
||||
$this->escalateToTier3($project, 'update', $externalId, $dto, 'portal_unreachable', $e);
|
||||
} catch (SupplierClientException|SupplierAuthException $e) {
|
||||
try {
|
||||
$this->tier2->updateProject($externalId, $dto);
|
||||
$this->alertFailoverToForm($project, 'update', $e);
|
||||
|
||||
return;
|
||||
} catch (Throwable $tier2Error) {
|
||||
$this->escalateToTier3(
|
||||
$project, 'update', $externalId, $dto,
|
||||
$this->classifyTier2Failure($tier2Error), $tier2Error,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function escalateToTier3(
|
||||
Project $project,
|
||||
string $operation,
|
||||
?int $externalId,
|
||||
SupplierProjectDto $dto,
|
||||
string $reason,
|
||||
Throwable $cause,
|
||||
): never {
|
||||
$row = SupplierManualSyncQueue::create([
|
||||
'project_id' => $project->id,
|
||||
'platform' => $dto->platform,
|
||||
'operation' => $operation,
|
||||
'external_id' => $externalId !== null ? (string) $externalId : null,
|
||||
'payload_snapshot' => [
|
||||
'signal_type' => $dto->signalType,
|
||||
'unique_key' => $dto->uniqueKey,
|
||||
'limit' => $dto->limit,
|
||||
'workdays' => $dto->workdays,
|
||||
'regions' => $dto->regions,
|
||||
'regions_reverse' => $dto->regionsReverse,
|
||||
'status' => $dto->status,
|
||||
],
|
||||
'failure_reason' => $reason,
|
||||
'status' => 'pending',
|
||||
'created_at' => now(),
|
||||
]);
|
||||
|
||||
$this->mailer->to((string) config('services.supplier.alert_email'))
|
||||
->queue(new SupplierCriticalAlertMail(
|
||||
alertType: 'manual_required',
|
||||
details: "Project #{$project->id} ({$dto->platform}/{$dto->uniqueKey}) — {$operation} queued #{$row->id}, reason: {$reason}. Cause: ".mb_substr($cause->getMessage(), 0, 300),
|
||||
));
|
||||
|
||||
throw new TierEscalatedException($row->id, $reason);
|
||||
}
|
||||
|
||||
private function alertFailoverToForm(Project $project, string $operation, Throwable $cause): void
|
||||
{
|
||||
$this->mailer->to((string) config('services.supplier.alert_email'))
|
||||
->queue(new SupplierCriticalAlertMail(
|
||||
alertType: 'failover_to_form',
|
||||
details: "Project #{$project->id} {$operation}: Tier 1 (AJAX) failed, Tier 2 (browser) succeeded. Cause: ".mb_substr($cause->getMessage(), 0, 300),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Портальная сверка: ищет уже существующий проект на портале по тройке
|
||||
* (platform, signal_type, unique_key). Возвращает external_id найденного
|
||||
* или null. Spec §4.4 шаг 2, §7.
|
||||
*/
|
||||
private function findOnPortal(SupplierProjectDto $dto): ?int
|
||||
{
|
||||
foreach ($this->tier1->listProjects() as $row) {
|
||||
if (
|
||||
($row['platform'] ?? null) === $dto->platform
|
||||
&& ($row['signal_type'] ?? null) === $dto->signalType
|
||||
&& ($row['unique_key'] ?? null) === $dto->uniqueKey
|
||||
) {
|
||||
return (int) ($row['id'] ?? 0) ?: null;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function classifyTier2Failure(Throwable $e): string
|
||||
{
|
||||
$msg = mb_strtolower($e->getMessage());
|
||||
if (str_contains($msg, 'auth') || str_contains($msg, 'login')) {
|
||||
return 'auth_failure';
|
||||
}
|
||||
if (str_contains($msg, 'selector') || str_contains($msg, 'form')) {
|
||||
return 'form_selector_break';
|
||||
}
|
||||
|
||||
return 'form_save_error';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Supplier\Channel;
|
||||
|
||||
use App\Services\Supplier\Dto\SupplierProjectDto;
|
||||
use App\Services\Supplier\PlaywrightBridge;
|
||||
|
||||
/**
|
||||
* Ярус 2: водит форму «Мои проекты» supplier-портала через manage-project.js.
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-19-supplier-project-channel-failover-design.md §4.3
|
||||
*/
|
||||
final class FormProjectChannel implements SupplierProjectChannel
|
||||
{
|
||||
public function __construct(
|
||||
private readonly PlaywrightBridge $bridge,
|
||||
) {}
|
||||
|
||||
public function createProject(SupplierProjectDto $dto): int
|
||||
{
|
||||
$out = $this->callBridge('create', null, $dto);
|
||||
$id = (int) ($out['external_id'] ?? 0);
|
||||
if ($id === 0) {
|
||||
throw new \RuntimeException('FormProjectChannel: create returned empty external_id');
|
||||
}
|
||||
|
||||
return $id;
|
||||
}
|
||||
|
||||
public function updateProject(int $externalId, SupplierProjectDto $dto): void
|
||||
{
|
||||
$out = $this->callBridge('update', $externalId, $dto);
|
||||
if (($out['ok'] ?? false) !== true) {
|
||||
throw new \RuntimeException('FormProjectChannel: update did not return ok=true');
|
||||
}
|
||||
}
|
||||
|
||||
public function listProjects(): array
|
||||
{
|
||||
$out = $this->callBridge('list', null, null);
|
||||
|
||||
return (array) ($out['projects'] ?? []);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function callBridge(string $operation, ?int $externalId, ?SupplierProjectDto $dto): array
|
||||
{
|
||||
return $this->bridge->run([
|
||||
'script' => 'manage-project.js',
|
||||
'operation' => $operation,
|
||||
'externalId' => $externalId,
|
||||
'dto' => $dto !== null ? $this->mapDto($dto) : null,
|
||||
'login' => (string) config('services.supplier.login'),
|
||||
'password' => (string) config('services.supplier.password'),
|
||||
'url' => (string) config('services.supplier.portal_url'),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function mapDto(SupplierProjectDto $dto): array
|
||||
{
|
||||
return [
|
||||
'tag' => $dto->uniqueKey,
|
||||
'name' => $dto->uniqueKey,
|
||||
'platforms' => [$dto->platform],
|
||||
'signal_type' => $dto->signalType,
|
||||
'limit' => $dto->limit,
|
||||
'workdays' => $dto->workdays,
|
||||
'regions' => $dto->regions,
|
||||
'region_mode' => $dto->regionsReverse ? 'exclude' : 'include',
|
||||
'domains' => $dto->signalType === 'site' ? [$dto->uniqueKey] : [],
|
||||
'active' => $dto->status === 'active',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Supplier\Channel;
|
||||
|
||||
use App\Services\Supplier\Dto\SupplierProjectDto;
|
||||
|
||||
/**
|
||||
* Контракт миграции проекта Лидерра → поставщик crm.bp-gr.ru.
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-19-supplier-project-channel-failover-design.md §4.1
|
||||
*
|
||||
* Реализации (ярусы резерва):
|
||||
* - AjaxProjectChannel — rt-project-* HTTP (primary, быстрый).
|
||||
* - FormProjectChannel — Playwright водит форму «Мои проекты» (fallback).
|
||||
* - FailoverProjectChannel — декоратор-оркестратор (ярус 1 → ярус 2 → ярус 3 queue).
|
||||
*/
|
||||
interface SupplierProjectChannel
|
||||
{
|
||||
/**
|
||||
* Создаёт проект на портале, возвращает supplier external_id.
|
||||
*/
|
||||
public function createProject(SupplierProjectDto $dto): int;
|
||||
|
||||
/**
|
||||
* Обновляет существующий проект (квота/дни/регионы).
|
||||
*/
|
||||
public function updateProject(int $externalId, SupplierProjectDto $dto): void;
|
||||
|
||||
/**
|
||||
* Список проектов с портала — для дедуп-сверки и закрытия яруса 3.
|
||||
*
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function listProjects(): array;
|
||||
}
|
||||
@@ -33,6 +33,9 @@ final readonly class SupplierProjectDto
|
||||
array $regions,
|
||||
public bool $regionsReverse, // false = include (default), true = exclude
|
||||
public string $status, // active / paused
|
||||
public string $tag = '_lidpotok',
|
||||
/** @var array<int, string> */
|
||||
public array $platforms = [],
|
||||
) {
|
||||
// Canonical order for deterministic equals() vs PG jsonb non-deterministic order.
|
||||
// sort() reorders in-place AND re-indexes keys 0..N-1 (PHP guarantees list-semantics).
|
||||
|
||||
@@ -52,4 +52,46 @@ class PlaywrightBridge
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic Node-скрипт runner: запускает playwright/<script> с JSON stdin,
|
||||
* возвращает декодированный JSON stdout. Используется FormProjectChannel
|
||||
* (manage-project.js — ярус 2 резерва канала миграции проектов).
|
||||
*
|
||||
* @param array<string, mixed> $args обязательный ключ 'script'; остальное — payload на stdin.
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function run(array $args): array
|
||||
{
|
||||
$script = $args['script'] ?? null;
|
||||
if (! is_string($script) || $script === '') {
|
||||
throw new \InvalidArgumentException('PlaywrightBridge::run requires non-empty "script" key');
|
||||
}
|
||||
|
||||
$payload = $args;
|
||||
unset($payload['script']);
|
||||
|
||||
$process = $this->processFactory->create(
|
||||
['node', 'playwright/'.$script],
|
||||
base_path(),
|
||||
);
|
||||
$process->setInput(json_encode($payload, JSON_THROW_ON_ERROR));
|
||||
$process->setTimeoutSeconds(self::TIMEOUT_SECONDS);
|
||||
$process->run();
|
||||
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new \RuntimeException(
|
||||
"PlaywrightBridge::run({$script}) exit code {$process->getExitCode()}: {$process->getErrorOutput()}",
|
||||
);
|
||||
}
|
||||
|
||||
$output = json_decode($process->getOutput(), true);
|
||||
if (! is_array($output)) {
|
||||
throw new \RuntimeException(
|
||||
"PlaywrightBridge::run({$script}) returned non-array output: {$process->getOutput()}",
|
||||
);
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,21 +7,19 @@ namespace App\Services\Supplier;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Streaming-парсер CSV-экспорта `/admin/report/index?type=49` поставщика.
|
||||
* Streaming-парсер CSV-отчёта «Запрос номеров» supplier-портала crm.bp-gr.ru.
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-11-plan4-billing-csv-admin-design.md §5.2
|
||||
* Ожидаемые столбцы: vid;project;tag;phone;phones;time (placeholder; уточнится
|
||||
* после Plan 3 Tasks 1-2 discovery с credentials поставщика).
|
||||
* Spec: docs/superpowers/specs/2026-05-18-supplier-csv-reconcile-channel-design.md §4.1
|
||||
* Столбцы: Name;Tag;Phone — 3 колонки. vid и время в этом отчёте отсутствуют.
|
||||
*
|
||||
* Возвращает Generator — вызывающий (CsvReconcileJob) сам решает, сколько
|
||||
* копить в памяти. BOM + CRLF поддерживаются. Malformed rows skip + log.
|
||||
* Возвращает Generator. BOM + CRLF поддерживаются. Malformed rows skip + log.
|
||||
*/
|
||||
final class SupplierCsvParser
|
||||
{
|
||||
private const EXPECTED_COLUMNS = 6;
|
||||
private const EXPECTED_COLUMNS = 3;
|
||||
|
||||
/**
|
||||
* @return iterable<int, array{vid: string, project: string, phone: string, time: int}>
|
||||
* @return iterable<int, array{project: string, tag: string, phone: string}>
|
||||
*/
|
||||
public function parse(string $rawCsv): iterable
|
||||
{
|
||||
@@ -29,7 +27,7 @@ final class SupplierCsvParser
|
||||
return;
|
||||
}
|
||||
|
||||
// Убираем BOM (UTF-8 BOM = EF BB BF)
|
||||
// Убираем UTF-8 BOM (EF BB BF)
|
||||
if (str_starts_with($rawCsv, "\xEF\xBB\xBF")) {
|
||||
$rawCsv = substr($rawCsv, 3);
|
||||
}
|
||||
@@ -65,10 +63,9 @@ final class SupplierCsvParser
|
||||
}
|
||||
|
||||
yield [
|
||||
'vid' => (string) $cols[0],
|
||||
'project' => (string) $cols[1],
|
||||
'phone' => (string) $cols[3],
|
||||
'time' => (int) $cols[5],
|
||||
'project' => (string) $cols[0],
|
||||
'tag' => (string) $cols[1],
|
||||
'phone' => (string) $cols[2],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Supplier;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Глобальный режим экспорта проектов поставщику (system_settings).
|
||||
* 'online' — sync сразу при create/edit с полными параметрами;
|
||||
* 'batch' — каркас сразу + полные параметры ночным SyncSupplierProjectsJob (18:00).
|
||||
* Spec: docs/superpowers/specs/2026-05-20-project-migration-redesign-design.md §4.1.
|
||||
*/
|
||||
final class SupplierExportMode
|
||||
{
|
||||
public const ONLINE = 'online';
|
||||
|
||||
public const BATCH = 'batch';
|
||||
|
||||
public static function current(): string
|
||||
{
|
||||
$value = DB::table('system_settings')->where('key', 'supplier_export_mode')->value('value');
|
||||
|
||||
return $value === self::ONLINE ? self::ONLINE : self::BATCH;
|
||||
}
|
||||
|
||||
public static function isOnline(): bool
|
||||
{
|
||||
return self::current() === self::ONLINE;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ use App\Exceptions\Supplier\SupplierAuthException;
|
||||
use App\Exceptions\Supplier\SupplierClientException;
|
||||
use App\Exceptions\Supplier\SupplierTransientException;
|
||||
use App\Jobs\Supplier\RefreshSupplierSessionJob;
|
||||
use App\Models\SupplierProject;
|
||||
use App\Services\Supplier\Dto\SupplierProjectDto;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
@@ -21,14 +20,25 @@ use Illuminate\Support\Facades\Cache;
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-10-supplier-integration-design.md §4.4
|
||||
*
|
||||
* Endpoints (placeholder, точные имена адаптируются после Task 1 discovery):
|
||||
* - GET /admin/rt-projects-load — список проектов
|
||||
* - POST /admin/rt-project-save — создание
|
||||
* - POST /admin/rt-project-update — обновление
|
||||
* - POST /admin/rt-project-delete — удаление
|
||||
* Endpoints (verified live 2026-05-19 через Playwright MCP recon —
|
||||
* создан LIDPOTOK_TEST_DELETE_ME, записаны сеть-запросы, проект удалён;
|
||||
* см. план Task 1 docs/superpowers/plans/2026-05-19-supplier-project-channel-failover.md):
|
||||
* - GET /admin/visit/rt-projects-load?src=none — массив всех rt-проектов tenant'а.
|
||||
* - POST /admin/visit/rt-project-save — create (id:0) ИЛИ update (id:N).
|
||||
* Body: application/json, большой Vuex-state. Минимально требуемые поля
|
||||
* описаны в toPayload(). Response:
|
||||
* success → HTTP 200 + {"status":"OK","message":"","result":null,"id":"<string>"}
|
||||
* error → HTTP 200 + {"status":"Error","message":"<reason>","result":null}
|
||||
* ID в ответе — строка (например, "12721245"); приводим к int (fits в int64).
|
||||
* Один save c B1+B2+B3 (несколько включённых src*-флагов) создаёт N rt-проектов
|
||||
* (по одному на каждый включённый канал); `id` в response — последний из созданных.
|
||||
* В нашем use case toPayload() отправляет ровно один платформенный флаг.
|
||||
* - POST /admin/visit/rt-project-delete — удаление по id.
|
||||
* Body: application/json {"id":"<string>"}. Response: тот же конверт {status,message,result}.
|
||||
*
|
||||
* Авторизация: PHPSESSID cookie + X-CSRF-Token header (Redis cache 'supplier:session').
|
||||
* На 401/403 — single retry через dispatch_sync(RefreshSupplierSessionJob).
|
||||
* На HTTP 200 + status:"Error" — выбрасываем SupplierClientException с message портала.
|
||||
*/
|
||||
class SupplierPortalClient
|
||||
{
|
||||
@@ -37,106 +47,236 @@ class SupplierPortalClient
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Идемпотентно обеспечивает наличие supplier_project-записи для переданной
|
||||
* тройки (platform, signalType, uniqueKey). Если запись уже существует —
|
||||
* возвращает её id. Иначе — создаёт проект на стороне поставщика через
|
||||
* saveProject() и сохраняет новую запись supplier_projects.
|
||||
* Сырые строки rt-проектов с портала.
|
||||
*
|
||||
* Используется SyncSupplierProjectJob (Plan 5 Task 4).
|
||||
* Verified live 2026-05-19: GET /admin/visit/rt-projects-load?src=none
|
||||
* возвращает объект-конверт {projects:[...], tags, users, tokens, categories}
|
||||
* — НЕ голый массив. Извлекаем `projects`. Строка проекта:
|
||||
* {id:string, tag, src, name:"B<n>_<key>", type:"hosts|calls|sms", lim,
|
||||
* workdays, regions, regions_reverse, content, ...}.
|
||||
* Приведение к контрактной форме SupplierProjectChannel — в AjaxProjectChannel.
|
||||
*
|
||||
* В тестах метод мокируется через $this->mock(SupplierPortalClient::class) —
|
||||
* реальное тело не вызывается.
|
||||
*
|
||||
* @param string $platform B1 / B2 / B3
|
||||
* @param string $signalType site / call / sms
|
||||
* @param string $uniqueKey domain / phone / sender+keyword / sender
|
||||
*/
|
||||
public function ensureSupplierProject(string $platform, string $signalType, string $uniqueKey): int
|
||||
{
|
||||
$existing = SupplierProject::query()
|
||||
->where('platform', $platform)
|
||||
->where('signal_type', $signalType)
|
||||
->where('unique_key', $uniqueKey)
|
||||
->first();
|
||||
|
||||
if ($existing !== null) {
|
||||
return $existing->id;
|
||||
}
|
||||
|
||||
$dto = new SupplierProjectDto(
|
||||
platform: $platform,
|
||||
signalType: $signalType,
|
||||
uniqueKey: $uniqueKey,
|
||||
limit: 0,
|
||||
workdays: [1, 2, 3, 4, 5, 6, 7],
|
||||
regions: [],
|
||||
regionsReverse: false,
|
||||
status: 'active',
|
||||
);
|
||||
|
||||
$externalId = $this->saveProject($dto);
|
||||
|
||||
$sp = SupplierProject::query()->create([
|
||||
'platform' => $platform,
|
||||
'signal_type' => $signalType,
|
||||
'unique_key' => $uniqueKey,
|
||||
'supplier_external_id' => (string) $externalId,
|
||||
'current_limit' => 0,
|
||||
'current_workdays' => [1, 2, 3, 4, 5, 6, 7],
|
||||
'current_regions' => null,
|
||||
'sync_status' => 'ok',
|
||||
]);
|
||||
|
||||
return $sp->id;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, mixed>
|
||||
* @return array<int, array<string, mixed>>
|
||||
*/
|
||||
public function listProjects(): array
|
||||
{
|
||||
$response = $this->request('GET', '/admin/rt-projects-load');
|
||||
$response = $this->request('GET', '/admin/visit/rt-projects-load', ['src' => 'none']);
|
||||
|
||||
return $response->json() ?? [];
|
||||
$body = $response->json();
|
||||
$projects = is_array($body) ? ($body['projects'] ?? []) : [];
|
||||
|
||||
return is_array($projects) ? array_values($projects) : [];
|
||||
}
|
||||
|
||||
public function saveProject(SupplierProjectDto $dto): int
|
||||
{
|
||||
$response = $this->request('POST', '/admin/rt-project-save', $this->toPayload($dto));
|
||||
$response = $this->request(
|
||||
'POST',
|
||||
'/admin/visit/rt-project-save',
|
||||
$this->toPayload($dto, externalId: 0),
|
||||
asJson: true,
|
||||
);
|
||||
|
||||
$this->assertStatusOk($response, '/admin/visit/rt-project-save');
|
||||
|
||||
return (int) ($response->json('id') ?? 0);
|
||||
}
|
||||
|
||||
public function updateProject(int $externalId, SupplierProjectDto $dto): void
|
||||
{
|
||||
$this->request('POST', '/admin/rt-project-update', array_merge(
|
||||
['id' => $externalId],
|
||||
$this->toPayload($dto)
|
||||
));
|
||||
$response = $this->request(
|
||||
'POST',
|
||||
'/admin/visit/rt-project-save',
|
||||
$this->toPayload($dto, externalId: $externalId),
|
||||
asJson: true,
|
||||
);
|
||||
|
||||
$this->assertStatusOk($response, '/admin/visit/rt-project-save');
|
||||
}
|
||||
|
||||
/**
|
||||
* R5: один save с флагами всех dto->platforms → портал создаёт N rt-проектов,
|
||||
* портал делит лимит сам (R6). Ответ rt-project-save отдаёт id последнего →
|
||||
* дочитываем listProjects и матчим по name+tag (R-SAVE вариант а, Task 1 finding).
|
||||
*
|
||||
* @return array<string, int> [platform => external_id]
|
||||
*/
|
||||
public function saveProjectMultiFlag(SupplierProjectDto $dto): array
|
||||
{
|
||||
$response = $this->request(
|
||||
'POST', '/admin/visit/rt-project-save',
|
||||
$this->toPayload($dto, externalId: 0), asJson: true,
|
||||
);
|
||||
$this->assertStatusOk($response, '/admin/visit/rt-project-save');
|
||||
|
||||
$srcToPlatform = ['rt' => 'B1', 'bl' => 'B2', 'mt' => 'B3'];
|
||||
$out = [];
|
||||
foreach ($this->listProjects() as $p) {
|
||||
// Real portal returns name='B1_<identifier>' and identifier in 'content'.
|
||||
// Test mocks omit 'content' and put identifier directly in 'name' — fall back to 'name'
|
||||
// when 'content' is absent so both shapes work.
|
||||
$identifier = $p['content'] ?? $p['name'] ?? null;
|
||||
if ($identifier !== $dto->uniqueKey || ($p['tag'] ?? null) !== $dto->tag) {
|
||||
continue;
|
||||
}
|
||||
$platform = $srcToPlatform[$p['src'] ?? ''] ?? null;
|
||||
if ($platform !== null && in_array($platform, $dto->platforms !== [] ? $dto->platforms : [$dto->platform], true)) {
|
||||
$out[$platform] = (int) $p['id'];
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function deleteProject(int $externalId): void
|
||||
{
|
||||
$this->request('POST', '/admin/rt-project-delete', ['id' => $externalId]);
|
||||
$response = $this->request(
|
||||
'POST',
|
||||
'/admin/visit/rt-project-delete',
|
||||
['id' => (string) $externalId],
|
||||
asJson: true,
|
||||
);
|
||||
|
||||
$this->assertStatusOk($response, '/admin/visit/rt-project-delete');
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /admin/report/index?type=49 — CSV-экспорт лидов за окно [from, to].
|
||||
* Auth/retry семантика наследуется от request() (PHPSESSID + X-CSRF-Token +
|
||||
* 401 → RefreshSession + 5xx → SupplierTransientException + 4xx → SupplierClientException).
|
||||
*
|
||||
* Возвращает raw CSV-body (UTF-8 + BOM, CRLF). Парсинг — снаружи через
|
||||
* SupplierCsvParser (streaming через generator).
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-11-plan4-billing-csv-admin-design.md §5.1
|
||||
* Portal-конверт ответа: HTTP 200 + {"status":"OK"|"Error", "message":"...", ...}.
|
||||
* Текстовая бизнес-ошибка приходит с HTTP 200 — HTTP-уровень обрабатывает только
|
||||
* 401/403/4xx/5xx; status=Error превращаем в SupplierClientException здесь.
|
||||
*/
|
||||
public function downloadLeadsCsv(CarbonInterface $from, CarbonInterface $to): string
|
||||
private function assertStatusOk(Response $response, string $path): void
|
||||
{
|
||||
$response = $this->request('GET', '/admin/report/index', [
|
||||
'type' => 49,
|
||||
'from' => $from->format('Y-m-d H:i:s'),
|
||||
'to' => $to->format('Y-m-d H:i:s'),
|
||||
]);
|
||||
$status = $response->json('status');
|
||||
|
||||
if ($status === 'OK') {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($status === 'Error') {
|
||||
$message = (string) ($response->json('message') ?? 'unknown');
|
||||
throw new SupplierClientException(
|
||||
"Supplier rejected {$path}: {$message}",
|
||||
httpStatus: $response->status(),
|
||||
responseBody: $response->body(),
|
||||
);
|
||||
}
|
||||
|
||||
// Неконвертный ответ — считаем как client-error (контракт сломан).
|
||||
throw new SupplierClientException(
|
||||
"Supplier returned unexpected envelope on {$path}: status={$status}",
|
||||
httpStatus: $response->status(),
|
||||
responseBody: $response->body(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Заказывает у поставщика отчёт «Запрос номеров» за диапазон [from, to].
|
||||
* Возвращает report_id для последующего waitReportReady / downloadReport.
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-18-supplier-csv-reconcile-channel-design.md §4.3.
|
||||
*
|
||||
* Discovery T3 verified 2026-05-19 (Playwright MCP, см. snapshot
|
||||
* `supplier-api-configured-2026-05-19.png`):
|
||||
* - POST /admin/report/save-report принимает JSON {reportForm:{selectType:49},
|
||||
* reportFilter:{dateFrom, dateTo, ...defaults}} и возвращает строку "OK"
|
||||
* (НЕ JSON с id).
|
||||
* - id извлекается отдельным GET /admin/report/load-reports — это массив
|
||||
* отчётов в DESC-порядке, ищем первый с title
|
||||
* "Запрос номеров с {from} по {to}".
|
||||
*/
|
||||
public function requestNumbersReport(CarbonInterface $from, CarbonInterface $to): int
|
||||
{
|
||||
$this->request('POST', '/admin/report/save-report', [
|
||||
'reportForm' => ['selectType' => 49],
|
||||
'reportFilter' => [
|
||||
'dateFrom' => $from->format('Y-m-d'),
|
||||
'dateTo' => $to->format('Y-m-d'),
|
||||
'slug' => null,
|
||||
'rate' => 'all',
|
||||
'dnss' => '',
|
||||
'phones' => '',
|
||||
'prophones' => 'curr',
|
||||
'users' => [],
|
||||
'domains' => [],
|
||||
'utcs' => [],
|
||||
'types' => ['phones'],
|
||||
'xls' => false,
|
||||
'project_id' => null,
|
||||
'state_id' => 0,
|
||||
'gck_tech' => 'gck',
|
||||
],
|
||||
], asJson: true);
|
||||
|
||||
$expectedTitle = sprintf(
|
||||
'Запрос номеров с %s по %s',
|
||||
$from->format('Y-m-d'),
|
||||
$to->format('Y-m-d'),
|
||||
);
|
||||
|
||||
$list = $this->request('GET', '/admin/report/load-reports')->json();
|
||||
if (! is_array($list)) {
|
||||
throw new SupplierClientException('load-reports returned non-array response');
|
||||
}
|
||||
|
||||
foreach ($list as $row) {
|
||||
if (! is_array($row)) {
|
||||
continue;
|
||||
}
|
||||
if (($row['title'] ?? null) === $expectedTitle) {
|
||||
return (int) ($row['id'] ?? 0);
|
||||
}
|
||||
}
|
||||
|
||||
throw new SupplierClientException(
|
||||
"Report just queued (title '{$expectedTitle}') not found in load-reports",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Опрашивает статус отчёта до значения «Обработан» (status="1").
|
||||
* На таймаут — SupplierTransientException.
|
||||
*
|
||||
* Discovery T3 verified: status — строка "0" (в обработке) / "1" (готов);
|
||||
* endpoint — общий GET /admin/report/load-reports (не /status?id=N).
|
||||
*/
|
||||
public function waitReportReady(int $reportId): void
|
||||
{
|
||||
$maxAttempts = 20;
|
||||
$delaySeconds = 3;
|
||||
|
||||
for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
|
||||
$list = $this->request('GET', '/admin/report/load-reports')->json();
|
||||
if (is_array($list)) {
|
||||
foreach ($list as $row) {
|
||||
if (! is_array($row)) {
|
||||
continue;
|
||||
}
|
||||
if ((int) ($row['id'] ?? 0) === $reportId && (string) ($row['status'] ?? '') === '1') {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($attempt < $maxAttempts) {
|
||||
sleep($delaySeconds);
|
||||
}
|
||||
}
|
||||
|
||||
throw new SupplierTransientException(
|
||||
"Report {$reportId} not ready after {$maxAttempts} polls"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Скачивает готовый отчёт как raw CSV-body (UTF-8 + BOM, CRLF).
|
||||
* Парсинг — снаружи через SupplierCsvParser.
|
||||
*
|
||||
* Discovery T3 verified: endpoint GET /admin/report/getfile?id=N — совпадает с placeholder.
|
||||
*/
|
||||
public function downloadReport(int $reportId): string
|
||||
{
|
||||
$response = $this->request('GET', '/admin/report/getfile', ['id' => $reportId]);
|
||||
|
||||
return $response->body();
|
||||
}
|
||||
@@ -144,7 +284,7 @@ class SupplierPortalClient
|
||||
/**
|
||||
* @param array<string, mixed> $body
|
||||
*/
|
||||
private function request(string $method, string $path, array $body = [], bool $isRetry = false): Response
|
||||
private function request(string $method, string $path, array $body = [], bool $isRetry = false, bool $asJson = false): Response
|
||||
{
|
||||
$session = $this->loadSession();
|
||||
$portalUrl = (string) config('services.supplier.portal_url');
|
||||
@@ -159,11 +299,14 @@ class SupplierPortalClient
|
||||
$request = $this->http
|
||||
->withCookies(['PHPSESSID' => $session['phpsessid']], $host)
|
||||
->withHeaders(['X-CSRF-Token' => $session['csrf']])
|
||||
->timeout(30);
|
||||
->connectTimeout(30)
|
||||
->timeout(60);
|
||||
|
||||
try {
|
||||
if ($method === 'GET') {
|
||||
$response = $request->get($url, $body);
|
||||
} elseif ($asJson) {
|
||||
$response = $request->asJson()->post($url, $body);
|
||||
} else {
|
||||
$response = $request->asForm()->post($url, $body);
|
||||
}
|
||||
@@ -211,9 +354,43 @@ class SupplierPortalClient
|
||||
);
|
||||
}
|
||||
|
||||
// Defense-in-depth: портал отдаёт логин-страницу с HTTP 200 при истекшей
|
||||
// сессии middle-of-use (вместо 401/403). Детектим Yii2-маркер и форсим
|
||||
// refresh+retry. Verified 2026-05-19: refresh-session.js ловит #loginform-username.
|
||||
if ($this->isHtmlLoginPage($response)) {
|
||||
if ($isRetry) {
|
||||
throw new SupplierAuthException(
|
||||
"Portal returned login page after refresh on {$path}",
|
||||
httpStatus: $response->status(),
|
||||
responseBody: $response->body(),
|
||||
);
|
||||
}
|
||||
try {
|
||||
dispatch_sync(app(RefreshSupplierSessionJob::class));
|
||||
} catch (\Throwable $e) {
|
||||
throw new SupplierAuthException(
|
||||
"Session refresh failed during HTML-login retry on {$path}: {$e->getMessage()}",
|
||||
httpStatus: $response->status(),
|
||||
previous: $e,
|
||||
);
|
||||
}
|
||||
|
||||
return $this->request($method, $path, $body, isRetry: true, asJson: $asJson);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
private function isHtmlLoginPage(Response $response): bool
|
||||
{
|
||||
$contentType = $response->header('Content-Type');
|
||||
if (! str_starts_with(mb_strtolower($contentType), 'text/html')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return preg_match('~loginform-(username|password)~i', $response->body()) === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{phpsessid: string, csrf: string, refreshed_at?: string}
|
||||
*/
|
||||
@@ -244,23 +421,69 @@ class SupplierPortalClient
|
||||
}
|
||||
|
||||
/**
|
||||
* NOTE: payload-shape — placeholder. Точные поля будут адаптированы
|
||||
* после Task 1 discovery + Task 2 spec §4.4 (отдельный fixup commit
|
||||
* перед Task 6 при расхождении).
|
||||
* Payload-shape для /admin/visit/rt-project-save (create + update).
|
||||
* Verified live 2026-05-19 (Playwright MCP recon — записан реальный JSON body
|
||||
* админ-формы «Добавить проект»; create=id:0, update=id:N).
|
||||
*
|
||||
* Mappings (наш DTO ↔ portal Vuex-state):
|
||||
* - platform: B1 → srcrt=true; B2 → srcbl=true; B3 → srcmt=true (single-true,
|
||||
* остальные false). Только один платформа за save — чтобы получить ровно
|
||||
* один rt-проект (множественные флаги создают N проектов, мы привязываемся
|
||||
* к одному external_id).
|
||||
* - signalType: site → type:"hosts"; call → type:"calls"; sms → type:"sms".
|
||||
* - uniqueKey → одновременно `name` (label проекта на портале — портал
|
||||
* префиксует "B<n>_" автоматически) и `content` (домен/телефон в полях
|
||||
* сбора).
|
||||
* - workdays: int[1..7] → string["1".."7"] (portal принимает строки).
|
||||
* - regions: int[]; regions_reverse: bool.
|
||||
* - status: "active" → true; "paused" → false.
|
||||
*
|
||||
* Дополнительно отправляем `tag:"_lidpotok"` для маркировки автоматизированных
|
||||
* проектов в админке портала + минимальный набор Vuex-defaults (show/depth/
|
||||
* multisignals/multigroup), которые портал ожидает в state-валидаторе.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function toPayload(SupplierProjectDto $dto): array
|
||||
private function toPayload(SupplierProjectDto $dto, int $externalId): array
|
||||
{
|
||||
$type = match ($dto->signalType) {
|
||||
'site' => 'hosts',
|
||||
'call' => 'calls',
|
||||
'sms' => 'sms',
|
||||
default => $dto->signalType,
|
||||
};
|
||||
|
||||
$platforms = $dto->platforms !== [] ? $dto->platforms : [$dto->platform];
|
||||
$srcrt = in_array('B1', $platforms, true);
|
||||
$srcbl = in_array('B2', $platforms, true);
|
||||
$srcmt = in_array('B3', $platforms, true);
|
||||
|
||||
// workdays: int → string (portal: ["1","2",...,"7"]).
|
||||
$workdays = array_map(static fn (int $d): string => (string) $d, $dto->workdays);
|
||||
|
||||
return [
|
||||
'platform' => $dto->platform,
|
||||
'signal_type' => $dto->signalType,
|
||||
'unique_key' => $dto->uniqueKey,
|
||||
'id' => $externalId,
|
||||
'tag' => $dto->tag,
|
||||
'name' => $dto->uniqueKey,
|
||||
'type' => $type,
|
||||
'content' => $dto->uniqueKey,
|
||||
'srcrt' => $srcrt,
|
||||
'srcbl' => $srcbl,
|
||||
'srcmt' => $srcmt,
|
||||
'srcmg' => false,
|
||||
'srclal' => false,
|
||||
'srcdop' => false,
|
||||
'srcwz' => false,
|
||||
'srcseg' => false,
|
||||
'limit' => $dto->limit,
|
||||
'workdays' => $dto->workdays,
|
||||
'workdays' => $workdays,
|
||||
'regions' => $dto->regions,
|
||||
'regions_reverse' => $dto->regionsReverse ? 1 : 0,
|
||||
'status' => $dto->status,
|
||||
'regions_reverse' => $dto->regionsReverse,
|
||||
'status' => $dto->status === 'active',
|
||||
'show' => true,
|
||||
'multisignals' => false,
|
||||
'multigroup' => false,
|
||||
'depth' => 1,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Services\Supplier;
|
||||
|
||||
use App\Models\Project;
|
||||
|
||||
/**
|
||||
* DRY-хелперы для группировки Лидерра-проектов по (subject × platform-set).
|
||||
*
|
||||
* Используется в:
|
||||
* - SyncSupplierProjectJob (онлайн-режим, один проект)
|
||||
* - SyncSupplierProjectsJob (ночной батч, все проекты)
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-20-project-migration-redesign-design.md §4.3
|
||||
* Plan: docs/superpowers/plans/2026-05-20-project-migration-redesign-plan-3-export.md Task 6
|
||||
*/
|
||||
final class SupplierProjectGrouping
|
||||
{
|
||||
/**
|
||||
* Строит unique_key для пары (project, platform):
|
||||
* site/call → signal_identifier (домен / телефон)
|
||||
* sms B2 → sender + '+' + keyword
|
||||
* sms B3 → sender
|
||||
*
|
||||
* Для ночного батч-джоба используйте buildUniqueKeyNoplatform() — он
|
||||
* выбирает B2-ключ автоматически при наличии keyword.
|
||||
*/
|
||||
public static function buildUniqueKey(Project $project, string $platform): string
|
||||
{
|
||||
if (in_array($project->signal_type, ['site', 'call'], true)) {
|
||||
return (string) $project->signal_identifier;
|
||||
}
|
||||
|
||||
// sms
|
||||
$sender = (string) ($project->sms_senders[0] ?? '');
|
||||
|
||||
if ($platform === 'B2') {
|
||||
return $sender.'+'.($project->sms_keyword ?? '');
|
||||
}
|
||||
|
||||
// B3
|
||||
return $sender;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unique identifier key без привязки к конкретной платформе
|
||||
* (для группировки в ночном батч-джобе):
|
||||
* site/call → signal_identifier
|
||||
* sms+keyword → sender+keyword (B2 ключ)
|
||||
* sms без keyword → sender (B3 ключ)
|
||||
*/
|
||||
public static function buildUniqueKeyAgnostic(Project $project): string
|
||||
{
|
||||
if (in_array($project->signal_type, ['site', 'call'], true)) {
|
||||
return (string) $project->signal_identifier;
|
||||
}
|
||||
|
||||
$sender = (string) ($project->sms_senders[0] ?? '');
|
||||
if ($project->sms_keyword !== null && $project->sms_keyword !== '') {
|
||||
return $sender.'+'.$project->sms_keyword;
|
||||
}
|
||||
|
||||
return $sender;
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает список uppercase platform-кодов для данного project.
|
||||
* Коды соответствуют CHECK constraint: 'B1' / 'B2' / 'B3'.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function resolvePlatforms(Project $project): array
|
||||
{
|
||||
if (in_array($project->signal_type, ['site', 'call'], true)) {
|
||||
return ['B1', 'B2', 'B3'];
|
||||
}
|
||||
|
||||
if ($project->signal_type === 'sms') {
|
||||
return ($project->sms_keyword !== null && $project->sms_keyword !== '')
|
||||
? ['B2', 'B3']
|
||||
: ['B3'];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns subjects (region codes 1..89) for a project.
|
||||
* Empty regions → [null] (one group, "Вся РФ" pool).
|
||||
*
|
||||
* @return list<int|null>
|
||||
*/
|
||||
public static function subjectsOf(Project $project): array
|
||||
{
|
||||
$regions = array_values((array) $project->regions);
|
||||
// @phpstan-ignore-next-line identical.alwaysFalse — PostgresIntArray PHPDoc non-empty, runtime can be empty
|
||||
if (count($regions) === 0) {
|
||||
return [null];
|
||||
}
|
||||
|
||||
return array_map(fn ($r) => (int) $r, $regions);
|
||||
}
|
||||
}
|
||||
@@ -9,26 +9,24 @@ use Carbon\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Pure function: распределение квоты daily_limit между platform B1/B2/B3.
|
||||
* Pure function: формула заказа у поставщика на (источник × субъект).
|
||||
*
|
||||
* Используется SyncSupplierProjectsJob для агрегирования daily_limit_target
|
||||
* всех активных Лидерра-проектов на одного supplier_project и распределения
|
||||
* суммарной квоты между B1/B2/B3 платформами.
|
||||
* Эпик миграции проектов (Plan 3): platform-split B1/B2/B3 удалён — портал
|
||||
* делит лимит сам (R6). Один лимит на группу eligible-клиентов:
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-10-supplier-integration-design.md §4.3-§4.4
|
||||
* order = max(наибольший_лимит, ceil(Σ_лимитов / 3))
|
||||
*
|
||||
* Distribution-формулы:
|
||||
* site/call:
|
||||
* B1 = ceil(total/3)
|
||||
* B2 = ceil((total - B1) / 2)
|
||||
* B3 = total - B1 - B2
|
||||
* sms-with-keyword (B1 не поддерживает СМС):
|
||||
* B1 = 0
|
||||
* B2 = ceil(total/2)
|
||||
* B3 = floor(total/2)
|
||||
* ceil(Σ/3) — ёмкость шаринга (лид продаётся ≤3 раз).
|
||||
* наиб — крупнейший клиент должен иметь шанс добрать.
|
||||
*
|
||||
* `allocate()` оставлен с прежней сигнатурой для временной совместимости
|
||||
* c SyncSupplierProjectsJob — внутри использует computeOrder, возвращает
|
||||
* DTO с одинаковым limit на любую platform/signalType.
|
||||
*
|
||||
* Workdays и regions — союзы (deduplicated, sorted) активных Лидерра-проектов,
|
||||
* eligible на targetDate (фильтр по weekday в Europe/Moscow).
|
||||
*
|
||||
* Spec: docs/superpowers/specs/2026-05-20-project-migration-redesign-design.md §4.5.
|
||||
*/
|
||||
final class SupplierQuotaAllocator
|
||||
{
|
||||
@@ -56,7 +54,9 @@ final class SupplierQuotaAllocator
|
||||
$workdaysUnion = self::unionInts($eligibleProjects->pluck('workdays'));
|
||||
$regionsUnion = self::unionInts($eligibleProjects->pluck('regions'));
|
||||
|
||||
$platformLimit = self::distributeForPlatform($signalType, $platform, $totalQuota);
|
||||
$platformLimit = self::computeOrder(
|
||||
$eligibleProjects->pluck('daily_limit')->map(fn ($v) => (int) $v)->all()
|
||||
);
|
||||
|
||||
return new SupplierProjectDto(
|
||||
platform: $platform,
|
||||
@@ -70,28 +70,26 @@ final class SupplierQuotaAllocator
|
||||
);
|
||||
}
|
||||
|
||||
private static function distributeForPlatform(string $signalType, string $platform, int $total): int
|
||||
/**
|
||||
* Заказ у поставщика на (источник × субъект): max(наибольший лимит, ceil(Σ/3)).
|
||||
*
|
||||
* ceil(Σ/3) — ёмкость шаринга (лид продаётся ≤3 раз).
|
||||
* наиб — крупнейший клиент должен иметь шанс добрать.
|
||||
*
|
||||
* Один лимит на группу; портал делит на B1/B2/B3 сам (R6 — наш split убран).
|
||||
*
|
||||
* @param array<int, int> $dailyLimits лимиты eligible-сегодня клиентов группы
|
||||
*/
|
||||
public static function computeOrder(array $dailyLimits): int
|
||||
{
|
||||
if ($signalType === 'sms') {
|
||||
if ($platform === 'B1') {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return $platform === 'B2'
|
||||
? (int) ceil($total / 2)
|
||||
: (int) floor($total / 2);
|
||||
if ($dailyLimits === []) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$b1 = (int) ceil($total / 3);
|
||||
$b2 = (int) ceil(($total - $b1) / 2);
|
||||
$b3 = $total - $b1 - $b2;
|
||||
$sum = array_sum($dailyLimits);
|
||||
$max = max($dailyLimits);
|
||||
|
||||
return match ($platform) {
|
||||
'B1' => $b1,
|
||||
'B2' => $b2,
|
||||
'B3' => $b3,
|
||||
default => 0,
|
||||
};
|
||||
return max($max, (int) ceil($sum / 3));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
/**
|
||||
* Канонический справочник субъектов РФ (1..89) — PHP-зеркало
|
||||
* resources/js/constants/regions.ts (конституционный порядок, ст. 65).
|
||||
* Sentinel 0 «Вся РФ» не входит (= NULL subject_code / пустой regions).
|
||||
*
|
||||
* ВАЖНО: при правке regions.ts синхронно править этот файл (тест RegionTagResolverTest
|
||||
* «mirrors regions.ts — exactly 89» ловит расхождение по count, но не по именам —
|
||||
* сверять имена вручную при изменениях).
|
||||
*/
|
||||
final class RussianRegions
|
||||
{
|
||||
/** @var array<int, string> code(1..89) => официальное имя субъекта */
|
||||
public const CODE_TO_NAME = [
|
||||
// 24 республики
|
||||
1 => 'Республика Адыгея',
|
||||
2 => 'Республика Алтай',
|
||||
3 => 'Республика Башкортостан',
|
||||
4 => 'Республика Бурятия',
|
||||
5 => 'Республика Дагестан',
|
||||
6 => 'Донецкая Народная Республика',
|
||||
7 => 'Республика Ингушетия',
|
||||
8 => 'Кабардино-Балкарская Республика',
|
||||
9 => 'Республика Калмыкия',
|
||||
10 => 'Карачаево-Черкесская Республика',
|
||||
11 => 'Республика Карелия',
|
||||
12 => 'Республика Коми',
|
||||
13 => 'Республика Крым',
|
||||
14 => 'Луганская Народная Республика',
|
||||
15 => 'Республика Марий Эл',
|
||||
16 => 'Республика Мордовия',
|
||||
17 => 'Республика Саха (Якутия)',
|
||||
18 => 'Республика Северная Осетия — Алания',
|
||||
19 => 'Республика Татарстан',
|
||||
20 => 'Республика Тыва',
|
||||
21 => 'Удмуртская Республика',
|
||||
22 => 'Республика Хакасия',
|
||||
23 => 'Чеченская Республика',
|
||||
24 => 'Чувашская Республика',
|
||||
// 9 краёв
|
||||
25 => 'Алтайский край',
|
||||
26 => 'Забайкальский край',
|
||||
27 => 'Камчатский край',
|
||||
28 => 'Краснодарский край',
|
||||
29 => 'Красноярский край',
|
||||
30 => 'Пермский край',
|
||||
31 => 'Приморский край',
|
||||
32 => 'Ставропольский край',
|
||||
33 => 'Хабаровский край',
|
||||
// 48 областей
|
||||
34 => 'Амурская область',
|
||||
35 => 'Архангельская область',
|
||||
36 => 'Астраханская область',
|
||||
37 => 'Белгородская область',
|
||||
38 => 'Брянская область',
|
||||
39 => 'Владимирская область',
|
||||
40 => 'Волгоградская область',
|
||||
41 => 'Вологодская область',
|
||||
42 => 'Воронежская область',
|
||||
43 => 'Запорожская область',
|
||||
44 => 'Ивановская область',
|
||||
45 => 'Иркутская область',
|
||||
46 => 'Калининградская область',
|
||||
47 => 'Калужская область',
|
||||
48 => 'Кемеровская область',
|
||||
49 => 'Кировская область',
|
||||
50 => 'Костромская область',
|
||||
51 => 'Курганская область',
|
||||
52 => 'Курская область',
|
||||
53 => 'Ленинградская область',
|
||||
54 => 'Липецкая область',
|
||||
55 => 'Магаданская область',
|
||||
56 => 'Московская область',
|
||||
57 => 'Мурманская область',
|
||||
58 => 'Нижегородская область',
|
||||
59 => 'Новгородская область',
|
||||
60 => 'Новосибирская область',
|
||||
61 => 'Омская область',
|
||||
62 => 'Оренбургская область',
|
||||
63 => 'Орловская область',
|
||||
64 => 'Пензенская область',
|
||||
65 => 'Псковская область',
|
||||
66 => 'Ростовская область',
|
||||
67 => 'Рязанская область',
|
||||
68 => 'Самарская область',
|
||||
69 => 'Саратовская область',
|
||||
70 => 'Сахалинская область',
|
||||
71 => 'Свердловская область',
|
||||
72 => 'Смоленская область',
|
||||
73 => 'Тамбовская область',
|
||||
74 => 'Тверская область',
|
||||
75 => 'Томская область',
|
||||
76 => 'Тульская область',
|
||||
77 => 'Тюменская область',
|
||||
78 => 'Ульяновская область',
|
||||
79 => 'Херсонская область',
|
||||
80 => 'Челябинская область',
|
||||
81 => 'Ярославская область',
|
||||
// 3 города федерального значения
|
||||
82 => 'Москва',
|
||||
83 => 'Санкт-Петербург',
|
||||
84 => 'Севастополь',
|
||||
// 1 автономная область
|
||||
85 => 'Еврейская автономная область',
|
||||
// 4 автономных округа
|
||||
86 => 'Ненецкий автономный округ',
|
||||
87 => 'Ханты-Мансийский автономный округ — Югра',
|
||||
88 => 'Чукотский автономный округ',
|
||||
89 => 'Ямало-Ненецкий автономный округ',
|
||||
];
|
||||
|
||||
/** @return array<string, int> name => code (обратный индекс) */
|
||||
public static function nameToCode(): array
|
||||
{
|
||||
return array_flip(self::CODE_TO_NAME);
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -17,6 +17,8 @@
|
||||
},
|
||||
"require-dev": {
|
||||
"barryvdh/laravel-ide-helper": "*",
|
||||
"deptrac/deptrac": "^4.6",
|
||||
"driftingly/rector-laravel": "^2.3",
|
||||
"fakerphp/faker": "^1.23",
|
||||
"infection/infection": "^0.32.7",
|
||||
"larastan/larastan": "*",
|
||||
@@ -26,8 +28,10 @@
|
||||
"laravel/pint": "^1.29",
|
||||
"mockery/mockery": "^1.6",
|
||||
"nunomaduro/collision": "^8.6",
|
||||
"nunomaduro/phpinsights": "*",
|
||||
"pestphp/pest": "^4.7",
|
||||
"pestphp/pest-plugin-laravel": "^4.1",
|
||||
"rector/rector": "^2.4",
|
||||
"roave/security-advisories": "dev-latest"
|
||||
},
|
||||
"autoload": {
|
||||
@@ -63,6 +67,9 @@
|
||||
"pint:test": "@php vendor/bin/pint --test",
|
||||
"test:parallel": "@php vendor/bin/pest --parallel --recreate-databases",
|
||||
"stan": "@php vendor/bin/phpstan analyse --memory-limit=512M",
|
||||
"rector": "@php vendor/bin/rector process --dry-run",
|
||||
"rector:fix": "@php vendor/bin/rector process",
|
||||
"insights": "@php artisan insights --no-interaction",
|
||||
"mutation": "@php vendor/bin/infection --threads=2 --min-msi=50",
|
||||
"audit-offline": "@composer audit --locked",
|
||||
"demo:seed": "@php artisan db:seed --class=DemoSeeder --force",
|
||||
@@ -101,7 +108,8 @@
|
||||
"allow-plugins": {
|
||||
"pestphp/pest-plugin": true,
|
||||
"php-http/discovery": true,
|
||||
"infection/extension-installer": true
|
||||
"infection/extension-installer": true,
|
||||
"dealerdirect/phpcodesniffer-composer-installer": true
|
||||
}
|
||||
},
|
||||
"minimum-stability": "stable",
|
||||
|
||||
Generated
+2588
-1
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use NunoMaduro\PhpInsights\Domain\Insights\ForbiddenDefineFunctions;
|
||||
use NunoMaduro\PhpInsights\Domain\Insights\ForbiddenFinalClasses;
|
||||
use NunoMaduro\PhpInsights\Domain\Insights\ForbiddenNormalClasses;
|
||||
use NunoMaduro\PhpInsights\Domain\Insights\ForbiddenPrivateMethods;
|
||||
use NunoMaduro\PhpInsights\Domain\Insights\ForbiddenTraits;
|
||||
use NunoMaduro\PhpInsights\Domain\Insights\SyntaxCheck;
|
||||
use NunoMaduro\PhpInsights\Domain\Metrics\Architecture\Classes;
|
||||
use SlevomatCodingStandard\Sniffs\Commenting\UselessFunctionDocCommentSniff;
|
||||
use SlevomatCodingStandard\Sniffs\Namespaces\AlphabeticallySortedUsesSniff;
|
||||
use SlevomatCodingStandard\Sniffs\TypeHints\DeclareStrictTypesSniff;
|
||||
use SlevomatCodingStandard\Sniffs\TypeHints\DisallowMixedTypeHintSniff;
|
||||
use SlevomatCodingStandard\Sniffs\TypeHints\ParameterTypeHintSniff;
|
||||
use SlevomatCodingStandard\Sniffs\TypeHints\PropertyTypeHintSniff;
|
||||
use SlevomatCodingStandard\Sniffs\TypeHints\ReturnTypeHintSniff;
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Preset
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option controls the default preset that will be used by PHP Insights
|
||||
| to make your code reliable, simple, and clean. However, you can always
|
||||
| adjust the `Metrics` and `Insights` below in this configuration file.
|
||||
|
|
||||
| Supported: "default", "laravel", "symfony", "magento2", "drupal", "wordpress"
|
||||
|
|
||||
*/
|
||||
|
||||
'preset' => 'laravel',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| IDE
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This options allow to add hyperlinks in your terminal to quickly open
|
||||
| files in your favorite IDE while browsing your PhpInsights report.
|
||||
|
|
||||
| Supported: "textmate", "macvim", "emacs", "sublime", "phpstorm",
|
||||
| "atom", "vscode".
|
||||
|
|
||||
| If you have another IDE that is not in this list but which provide an
|
||||
| url-handler, you could fill this config with a pattern like this:
|
||||
|
|
||||
| myide://open?url=file://%f&line=%l
|
||||
|
|
||||
*/
|
||||
|
||||
'ide' => null,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Configuration
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may adjust all the various `Insights` that will be used by PHP
|
||||
| Insights. You can either add, remove or configure `Insights`. Keep in
|
||||
| mind, that all added `Insights` must belong to a specific `Metric`.
|
||||
|
|
||||
*/
|
||||
|
||||
'exclude' => [
|
||||
// 'path/to/directory-or-file'
|
||||
],
|
||||
|
||||
'add' => [
|
||||
Classes::class => [
|
||||
ForbiddenFinalClasses::class,
|
||||
],
|
||||
],
|
||||
|
||||
'remove' => [
|
||||
// SyntaxCheck спавнит дочерний `php -l` процесс — на native-Windows возвращает
|
||||
// не-JSON и крашит PHP Insights (A1 backend-tooling, 20.05.2026). Избыточен:
|
||||
// синтаксис ловят Pint / Larastan / сам PHP. Стиль — владелец Pint (BT4, ADR-013).
|
||||
SyntaxCheck::class,
|
||||
AlphabeticallySortedUsesSniff::class,
|
||||
DeclareStrictTypesSniff::class,
|
||||
DisallowMixedTypeHintSniff::class,
|
||||
ForbiddenDefineFunctions::class,
|
||||
ForbiddenNormalClasses::class,
|
||||
ForbiddenTraits::class,
|
||||
ParameterTypeHintSniff::class,
|
||||
PropertyTypeHintSniff::class,
|
||||
ReturnTypeHintSniff::class,
|
||||
UselessFunctionDocCommentSniff::class,
|
||||
],
|
||||
|
||||
'config' => [
|
||||
ForbiddenPrivateMethods::class => [
|
||||
'title' => 'The usage of private methods is not idiomatic in Laravel.',
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Requirements
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may define a level you want to reach per `Insights` category.
|
||||
| When a score is lower than the minimum level defined, then an error
|
||||
| code will be returned. This is optional and individually defined.
|
||||
|
|
||||
*/
|
||||
|
||||
'requirements' => [
|
||||
// Anti-regression floors из baseline 20.05.2026 (Code 80 / Complexity 81 /
|
||||
// Architecture 75). Чуть ниже текущих — гейт ловит деградацию, не текущий долг.
|
||||
// Style НЕ гейтим — владелец стиля Pint (BT4, ADR-013). Security-check off —
|
||||
// дублирует roave/security-advisories + composer audit.
|
||||
'min-quality' => 78,
|
||||
'min-complexity' => 79,
|
||||
'min-architecture' => 73,
|
||||
'disable-security-check' => true,
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Threads
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may adjust how many threads (core) PHPInsights can use to perform
|
||||
| the analysis. This is optional, don't provide it and the tool will guess
|
||||
| the max core number available. It accepts null value or integer > 0.
|
||||
|
|
||||
*/
|
||||
|
||||
'threads' => null,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Timeout
|
||||
|--------------------------------------------------------------------------
|
||||
| Here you may adjust the timeout (in seconds) for PHPInsights to run before
|
||||
| a ProcessTimedOutException is thrown.
|
||||
| This accepts an int > 0. Default is 60 seconds, which is the default value
|
||||
| of Symfony's setTimeout function.
|
||||
|
|
||||
*/
|
||||
|
||||
'timeout' => 60,
|
||||
];
|
||||
@@ -7,6 +7,7 @@ namespace Database\Factories;
|
||||
use App\Models\Project;
|
||||
use App\Models\Tenant;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* @extends Factory<Project>
|
||||
@@ -20,7 +21,11 @@ class ProjectFactory extends Factory
|
||||
{
|
||||
return [
|
||||
'tenant_id' => Tenant::factory(),
|
||||
'name' => fake()->unique()->words(3, true),
|
||||
// Квирк #77: fake()->unique() создаёт новый UniqueGenerator на каждый
|
||||
// definition()-call → history между вызовами не сохраняется, uniqueness
|
||||
// внутри batch не гарантирована (коллизия (tenant_id, name) UNIQUE в
|
||||
// pest --parallel). Str::random(8) суффикс (62^8 ≈ 2e14) гасит коллизию.
|
||||
'name' => fake()->words(3, true).' '.Str::random(8),
|
||||
'type' => 'webhook',
|
||||
'is_active' => true,
|
||||
'daily_limit_target' => 10,
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Plan 6 (C9) — subject-level regions.
|
||||
*
|
||||
* +1 колонка projects.regions INT[] (1..89 коды субъектов РФ; пустой массив = вся РФ).
|
||||
* +1 GIN-индекс idx_projects_regions для outbound regions queries.
|
||||
* region_mask/region_mode остаются (dual-write) — удаление в Plan 6.5.
|
||||
*
|
||||
* Guard'ы: migrate:fresh грузит schema.sql v8.22 (где delta уже есть) до миграций,
|
||||
* поэтому каждый кусок применяется только при отсутствии (как Sprint 4 миграция).
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
if (! Schema::hasColumn('projects', 'regions')) {
|
||||
DB::statement("ALTER TABLE projects ADD COLUMN regions INT[] NOT NULL DEFAULT '{}'::INT[]");
|
||||
}
|
||||
|
||||
DB::statement('CREATE INDEX IF NOT EXISTS idx_projects_regions ON projects USING GIN (regions)');
|
||||
|
||||
DB::statement(
|
||||
'COMMENT ON COLUMN projects.regions IS '
|
||||
."'Subject-level region filter (1..89 коды субъектов РФ). Пустой массив = вся РФ. Plan 6 (v8.22).'"
|
||||
);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
DB::statement('DROP INDEX IF EXISTS idx_projects_regions');
|
||||
|
||||
if (Schema::hasColumn('projects', 'regions')) {
|
||||
Schema::table('projects', fn ($table) => $table->dropColumn('regions'));
|
||||
}
|
||||
}
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user