File size: 1,974 Bytes
afbb33a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
from .api import MikrotikAPI
from .Config import RouterConfig
from fastapi import HTTPException

import re
from typing import Tuple


class PhoneValidator:
    """Validator for Tanzanian phone numbers"""

    # Valid Tanzanian mobile operator prefixes
    VALID_PREFIXES = [
        "071",
        "074",
        "075",
        "076",
        "077",  # Vodacom
        "068",
        "069",  # Airtel
        "065",
        "067",  # Tigo
        "078",
        "079",  # TTCL
        "073",  # Zantel
        "061",
        "062",  # Halotel
    ]

    @staticmethod
    def validate_and_format(phone: str) -> Tuple[bool, str]:
        """
        Validates and formats Tanzanian phone numbers.
        Returns (is_valid, formatted_number)

        Valid format:
        - 255712345678 (12 digits starting with 255)
        """
        # Remove any spaces or special characters
        phone = re.sub(r"[\s\-\(\)]", "", phone)

        # Convert all formats to 255 format
        if phone.startswith("+255"):
            phone = "255" + phone[4:]
        elif phone.startswith("0"):
            phone = "255" + phone[1:]
        elif not phone.startswith("255"):
            return False, ""

        # Check if it matches the basic pattern (12 digits starting with 255)
        if not re.match(r"^255\d{9}$", phone):
            return False, ""

        # Check if the prefix is valid (check the digits after 255)
        prefix = "0" + phone[3:5]
        if prefix not in PhoneValidator.VALID_PREFIXES:
            return False, ""

        return True, phone


# Dependency to get MikrotikAPI instance
def get_mikrotik():
    config = RouterConfig()
    mikrotik = MikrotikAPI(config)
    try:
        if mikrotik.connect():
            yield mikrotik
        else:
            raise HTTPException(
                status_code=503,
                detail={"success": False, "message": "Could not connect to router"},
            )
    finally:
        mikrotik.close()