Skip to content

feat: add Iva, Clp, Phone and Region utilities - #23

Merged
gdespirito merged 2 commits into
mainfrom
chilean-utilities
Jul 11, 2026
Merged

feat: add Iva, Clp, Phone and Region utilities#23
gdespirito merged 2 commits into
mainfrom
chilean-utilities

Conversation

@gdespirito

@gdespirito gdespirito commented Jul 11, 2026

Copy link
Copy Markdown
Member

Summary

Second batch of the v2 work (follows #20): new Chilean utilities, each as its own cohesive class — no changes to Rut or any existing signatures.

New classes

  • Iva — Chilean VAT constants (RATE = 0.19, PERCENTAGE = 19) and calculations rounded to the nearest peso: Iva::of($net), Iva::add($net), Iva::net($gross), Iva::fromGross($gross).
  • Clp — Chilean peso formatting: Clp::format(1234567)'$1.234.567' (negatives and no-symbol supported) and Clp::parse('$1.234.567')1234567.
  • Phone — Chilean phone validation/normalization: accepts +56 9 8765 4321, 09-8765 4321, 987654321, etc. Detects mobile vs landline, formats to E.164 and human-readable. Stringable.
  • Region — int-backed enum with the 16 regions (official INE numbering): officialName(), romanNumeral() ('RM' for Metropolitana), capital(), northToSouth() and options() for selects.

Laravel

  • New cl_phone validation rule with English/Spanish translations, consistent with cl_rut.

Docs

  • README rewritten: quick-start snippet, feature table, one section per class.
  • Pending: hero banner image (blocked on OpenAI billing limit; will be attached as an issue asset to keep binaries out of the repo).

Test plan

  • 90 tests, 221 assertions passing (48 new)
  • PHPStan level 8 clean
  • Pint clean

🤖 Generated with Claude Code

https://claude.ai/code/session_01WvDYWr2Tx3diCV3NXGrKRX

Summary by CodeRabbit

  • New Features
    • Added Chilean peso (CLP) formatting/parsing helpers.
    • Added IVA (VAT) calculation utilities for net/gross and tax portions.
    • Added Chilean phone normalization, validation, mobile/landline classification, and formatting.
    • Added Chilean regions enum (names, roman numerals, capitals, north-to-south ordering, select options).
    • Added cl_phone Laravel validation rule with localized English/Spanish messages.
  • Documentation
    • Reorganized and refreshed the README and integration/rule examples.
  • Tests
    • Added unit tests for CLP, IVA, phone, region, plus Laravel validation tests for cl_phone.

- Iva: 19% VAT constants and net/gross calculations rounded to the peso
- Clp: format and parse Chilean peso amounts ($1.234.567)
- Phone: validate, normalize and format Chilean phone numbers (mobile/landline, E.164)
- Region: enum with the 16 regions (official names, roman numerals, capitals, north-to-south order)
- Laravel: new cl_phone validation rule with en/es translations
- README rewritten: feature table, per-class sections, quick-start snippet

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WvDYWr2Tx3diCV3NXGrKRX
@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 6a026665-4880-499a-9906-687e9ea1a545

📥 Commits

Reviewing files that changed from the base of the PR and between dc1b1be and c386afb.

📒 Files selected for processing (7)
  • README.md
  • src/Clp.php
  • src/Iva.php
  • src/Phone.php
  • tests/Unit/ClpTest.php
  • tests/Unit/IvaTest.php
  • tests/Unit/PhoneTest.php

📝 Walkthrough

Walkthrough

Adds CLP and IVA helpers, Chilean phone normalization and Laravel validation, a 16-region enum, corresponding tests, and substantially refreshed README documentation.

Changes

Chilean bundle features

Layer / File(s) Summary
CLP and IVA utilities
src/Clp.php, src/Iva.php, tests/Unit/ClpTest.php, tests/Unit/IvaTest.php
Adds peso formatting/parsing and IVA calculation APIs with rounding, conversion, extraction, and unit tests.
Phone normalization and Laravel validation
src/Phone.php, src/Laravel/..., lang/*/validation.php, tests/Laravel/ValidationTest.php, tests/Unit/PhoneTest.php
Adds phone parsing, validation, classification, formatting, Laravel rule registration, localized messages, and coverage for valid and invalid inputs.
Region enum and metadata helpers
src/Region.php, tests/Unit/RegionTest.php
Adds 16 Chilean regions with official names, numerals, capitals, geographic ordering, and select options.
README feature documentation
README.md
Reorganizes package introduction, installation, utility examples, Laravel guidance, upgrade notes, and closing headings.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Request
  participant Validator
  participant Phone
  participant Translation
  Request->>Validator: validate cl_phone input
  Validator->>Phone: Phone::check(value)
  Phone-->>Validator: validation result
  Validator->>Translation: resolve localized error
  Translation-->>Validator: translated message
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 78.26% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding Iva, Clp, Phone, and Region utilities.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chilean-utilities

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@README.md`:
- Around line 13-19: Update the README quick-start snippet to import or fully
qualify Rut, Iva, Clp, Phone, and Region from their Freshwork\ChileanBundle
namespaces so the example runs without class-not-found errors.

In `@src/Clp.php`:
- Around line 47-50: Update Clp::parse() to treat a minus sign as negative only
when it appears at the start of the amount, rather than using str_contains(),
while preserving digit extraction for valid formatted values. Add a regression
test covering a misplaced hyphen such as “1-234” and assert the expected parsing
behavior.

In `@src/Iva.php`:
- Around line 40-43: Define and document a single rounding policy for
Iva::add(), ensuring the net amount and IVA are combined before applying the
final rounding (or explicitly preserve the separate-rounding behavior). Update
the add() implementation and its documentation accordingly, and add a boundary
test covering a fractional input such as 1.4 against the documented expected
result.

In `@src/Phone.php`:
- Around line 55-63: Phone::normalize() currently strips arbitrary characters,
allowing malformed values through. Before removing formatting characters,
validate the original input against the permitted phone formatting characters
and reject unexpected characters; update Phone::check() and the cl_phone rule
behavior as needed, and add regression tests covering alphabetic and
text-prefixed inputs.
- Around line 110-115: The format() method currently assumes a one-digit area
code, causing valid landline numbers such as 452123456 to be formatted
incorrectly. Update format() to detect landline numbers and use the correct
two-digit area-code split, while preserving the existing formatting for other
number types.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 9e3b0629-6961-41ad-90a5-e7d85808bd19

📥 Commits

Reviewing files that changed from the base of the PR and between 7aee289 and dc1b1be.

📒 Files selected for processing (13)
  • README.md
  • lang/en/validation.php
  • lang/es/validation.php
  • src/Clp.php
  • src/Iva.php
  • src/Laravel/ChileanBundleServiceProvider.php
  • src/Phone.php
  • src/Region.php
  • tests/Laravel/ValidationTest.php
  • tests/Unit/ClpTest.php
  • tests/Unit/IvaTest.php
  • tests/Unit/PhoneTest.php
  • tests/Unit/RegionTest.php

Comment thread README.md
Comment thread src/Clp.php Outdated
Comment on lines +47 to +50
$negative = str_contains($amount, '-');
$digits = (string) preg_replace('/[^0-9]/', '', $amount);

return ($negative ? -1 : 1) * (int) $digits;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

git ls-files
printf '\n--- Clp.php outline ---\n'
ast-grep outline src/Clp.php --view expanded || true
printf '\n--- Clp.php lines ---\n'
cat -n src/Clp.php | sed -n '1,140p'
printf '\n--- tests/search for parse or hyphen cases ---\n'
rg -n "parse\(|Clp|1-234|negative|str_contains\\(\\$amount, '-'" src tests . || true

Repository: freshworkstudio/ChileanBundle

Length of output: 2777


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- tests/Unit/ClpTest.php ---'
cat -n tests/Unit/ClpTest.php

printf '\n%s\n' '--- README mentions CLP parse/format ---'
rg -n "Clp::parse|Clp::format|CLP|parse\\(" README.md src tests lang || true

printf '\n%s\n' '--- all references to Clp::parse ---'
rg -n "Clp::parse\\(" . || true

Repository: freshworkstudio/ChileanBundle

Length of output: 10850


Anchor the minus sign in Clp::parse()

str_contains($amount, '-') treats any hyphen as a negative sign, so 1-234 parses as -1234. Match only a leading sign or validate the full format, and add a regression test for misplaced hyphens.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/Clp.php` around lines 47 - 50, Update Clp::parse() to treat a minus sign
as negative only when it appears at the start of the amount, rather than using
str_contains(), while preserving digit extraction for valid formatted values.
Add a regression test covering a misplaced hyphen such as “1-234” and assert the
expected parsing behavior.

Comment thread src/Iva.php
Comment on lines +40 to +43
public static function add(int|float $net): int
{
return (int) round($net) + self::of($net);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '--- src/Iva.php ---\n'
cat -n src/Iva.php

printf '\n--- search for Iva references ---\n'
rg -n "Iva::add\(|class Iva|nearest peso|round" src tests . -g '!vendor' -g '!node_modules' || true

Repository: freshworkstudio/ChileanBundle

Length of output: 258


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- src/Iva.php ---'
cat -n src/Iva.php

echo
echo '--- Iva references ---'
rg -n "Iva::add\(|class Iva|nearest peso|round\(" src tests . -g '!vendor' -g '!node_modules' || true

Repository: freshworkstudio/ChileanBundle

Length of output: 4004


Use one rounding policy for Iva::add(). Iva::add() rounds the net amount and IVA separately, so float inputs can differ from rounding the gross total at the end (Iva::add(1.4) === 1 vs round(1.4 * 1.19) === 2). Define the intended behavior in the docs and add a boundary test.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/Iva.php` around lines 40 - 43, Define and document a single rounding
policy for Iva::add(), ensuring the net amount and IVA are combined before
applying the final rounding (or explicitly preserve the separate-rounding
behavior). Update the add() implementation and its documentation accordingly,
and add a boundary test covering a fractional input such as 1.4 against the
documented expected result.

Comment thread src/Phone.php
Comment thread src/Phone.php Outdated
- Clp::parse(): only a leading minus sign marks a negative amount
- Iva::add(): round the net to the peso before calculating IVA (documented policy)
- Phone::normalize(): reject input with unexpected characters instead of stripping them
- Phone::format(): split two-digit area codes correctly for regional landlines
- README: add missing use statements to the quick-start snippet

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WvDYWr2Tx3diCV3NXGrKRX
@gdespirito

Copy link
Copy Markdown
Member Author

Addressed all 5 CodeRabbit findings in the latest commit: anchored minus sign in Clp::parse(), single documented rounding policy for Iva::add() (net rounded first, IVA on the rounded net), Phone::normalize() now rejects unexpected characters, Phone::format() splits two-digit area codes correctly (+56 45 212 3456), and the README quick-start now includes the use statements. All with regression tests — 96 tests / 233 assertions passing.

@gdespirito
gdespirito merged commit 46f8f7d into main Jul 11, 2026
5 of 6 checks passed
@gdespirito
gdespirito deleted the chilean-utilities branch July 11, 2026 05:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant