Back to .md Directory

Product Requirements Document

| Document Info | Details |

May 2, 2026
0 downloads
0 views
ai
View source

Product Requirements Document

AT-Certified Invoicing Software System (Portugal)

Document InfoDetails
Version1.0
DateDecember 23, 2024
StatusDraft
ClassificationInternal

1. Executive Summary

1.1 Purpose

This document defines the complete product requirements for developing an invoicing software system that meets Portuguese Tax Authority (Autoridade Tributária e Aduaneira - AT) certification requirements. The system must comply with Decreto-Lei 28/2019, Portaria 363/2010, and associated technical regulations to legally operate in Portugal.

1.2 Scope

The product will provide:

  • Invoice creation, management, and archival
  • Digital signature generation with hash chain integrity
  • SAF-T (PT) file generation and export
  • ATCUD code generation and QR code embedding
  • Real-time and batch communication with AT systems
  • Multi-user access with audit trail capabilities

1.3 Target Users

  • Small and medium enterprises (SMEs) in Portugal
  • Accounting professionals and bookkeepers
  • Enterprise organizations requiring certified billing modules
  • Software integrators requiring white-label solutions

1.4 Success Criteria

MetricTarget
AT CertificationObtained within 60 days of submission
SAF-T Validation100% pass rate on AT validation tools
Signature Verification100% accuracy on cryptographic operations
System Uptime99.5% availability
Communication Success Rate≥99% successful AT transmissions

2. Legal and Regulatory Framework

2.1 Primary Legislation

LegislationDescriptionCompliance Priority
Decreto-Lei 28/2019Foundational invoicing lawMandatory
Decreto-Lei 198/2012e-Fatura communication systemMandatory
Portaria 363/2010Software certification requirementsMandatory
Portaria 302/2016SAF-T (PT) version 1.04_01Mandatory
Portaria 195/2020QR Code and ATCUD requirementsMandatory
Despacho 8632/2014Cryptographic specificationsMandatory

2.2 Certification Requirements

  • Certification Authority: Autoridade Tributária e Aduaneira (AT)
  • Application: Model 24 Declaration via Portal das Finanças
  • Cost: Free
  • Validity: Perpetual (until revoked)
  • Processing Time: Up to 30 days

2.3 Penalties for Non-Compliance

ViolationFine Range (EUR)
Fraudulent invoicing software€3,750 – €37,500
Failure to use certified software€1,500 – €18,750
Non-compliant software usage€1,500 – €18,750
Late/missing invoice communication€200 – €10,000
Missing SAF-T export€225 – €22,500

3. Functional Requirements

3.1 Document Management

FR-3.1.1 Document Types Support

The system SHALL support creation of the following document types:

CodeDocument TypeDescription
FTFaturaStandard invoice
FSFatura SimplificadaSimplified invoice (≤€1,000)
FRFatura-ReciboInvoice-receipt
NCNota de CréditoCredit note
NDNota de DébitoDebit note
GTGuia de TransporteTransport document
GRGuia de RemessaDelivery note
GAGuia de Movimentação de AtivosAsset movement guide
GCGuia de ConsignaçãoConsignment note
OROrçamentoQuotation
PPProformaProforma invoice
RCReciboReceipt

FR-3.1.2 Document Numbering

  • The system SHALL generate sequential document numbers per series
  • Format: [DocumentType] [SeriesCode]/[SequentialNumber]
  • Example: FT A/1, FT A/2, NC B/1
  • The system SHALL NOT allow gaps in sequential numbering
  • The system SHALL support multi-annual series continuation

FR-3.1.3 Document Status Management

Status CodeDescriptionAllowed Transitions
NNormal (active)→ A (cancel)
AAnulado (cancelled)Terminal state
TThird-party billingN/A
FBilledN/A
  • The system SHALL NOT allow deletion of issued documents
  • The system SHALL require cancellation reason for status A
  • Cancelled documents SHALL remain in system with full audit trail

FR-3.1.4 Document Content Requirements

Each invoice SHALL contain:

  • Seller identification (name, address, NIF)
  • Buyer identification (name, address, NIF when applicable)
  • Document type, series, and number
  • Issue date and system entry timestamp
  • Line items with description, quantity, unit price
  • Tax rates and amounts per line
  • Document totals (net, tax, gross)
  • Digital signature hash (4 characters)
  • Certification statement
  • ATCUD code
  • QR Code

3.2 Digital Signature System

FR-3.2.1 Cryptographic Implementation

RequirementSpecification
AlgorithmRSA asymmetric encryption
Key Size1024 bits
Hash FunctionSHA-1
Signature EncodingBase64 (no line breaks)
Signature Length172 characters
Key FormatPEM
Character EncodingUTF-8
Padding SchemePKCS#1 v1.5

FR-3.2.2 Signature Message Construction

The system SHALL construct the signing message as:

[Date];[SystemEntryDate];[DocumentNumber];[GrossTotal];[PreviousHash]
FieldFormatExample
DateYYYY-MM-DD2024-12-15
SystemEntryDateYYYY-MM-DDTHH:MM:SS2024-12-15T14:30:00
DocumentNumber[Type] [Series]/[Number]FT A/125
GrossTotalDecimal (2 places)1523.45
PreviousHash172 chars or emptyaWqC...Xy9=

FR-3.2.3 Hash Chain Integrity

  • The system SHALL store the complete 172-character hash for each document
  • Each document SHALL include the hash of the previous document in the same series
  • First document in a series SHALL have empty PreviousHash field
  • The system SHALL validate hash chain integrity on demand
  • Multi-annual series SHALL chain across year boundaries

FR-3.2.4 Printed Signature Display

The system SHALL display on printed documents:

[Char1]-[Char11]-[Char21]-[Char31]-Processado por programa certificado n.º XXXX/AT
  • Characters extracted from positions 1, 11, 21, 31 of Base64 signature
  • Certificate number obtained from AT after certification

3.3 ATCUD System

FR-3.3.1 ATCUD Structure

Format: ATCUD:[ValidationCode]-[SequentialNumber]

ComponentDescriptionFormat
ValidationCodeAT-assigned codeMin 8 chars, uppercase consonants + digits (excluding 0,1)
SequentialNumberDocument sequenceInteger

Example: ATCUD:AFY08799-445679

FR-3.3.2 Series Registration

The system SHALL support:

  • Registration of new document series with AT
  • Storage of validation codes per series
  • Automatic ATCUD generation on document creation
  • Series management interface for users
  • Webservice integration for automated registration

FR-3.3.3 Series Communication Data

When registering series, the system SHALL transmit:

  • Series identification code
  • Document type (per SAF-T classification)
  • Processing method (P=Program, M=Manual)
  • Starting sequential number
  • Expected usage start date

3.4 QR Code Generation

FR-3.4.1 QR Code Requirements

  • The system SHALL generate 2D QR codes per AT specifications
  • QR codes SHALL contain structured invoice data fields
  • QR codes SHALL be positioned consistently on documents
  • ATCUD SHALL appear immediately above QR code
  • Both elements SHALL appear on all pages of multi-page documents

FR-3.4.2 QR Code Data Fields

The QR code SHALL encode (per AT technical specification):

  • Issuer NIF
  • Buyer NIF (when applicable)
  • Buyer country code
  • Document type
  • Document status
  • Document date
  • Document unique ID (ATCUD)
  • Tax region (PT, PT-AC, PT-MA)
  • Tax base and amounts per rate
  • Withholding tax (if applicable)
  • Document total
  • Hash (4 characters)
  • Software certificate number

3.5 SAF-T (PT) Export

FR-3.5.1 Schema Compliance

  • The system SHALL export SAF-T files compliant with version 1.04_01
  • XSD Schema: saftpt1.04_01.xsd
  • The system SHALL pass AT validation tool checks
  • Maximum file size for portal upload: 40MB

FR-3.5.2 File Structure

<AuditFile>
  <Header>...</Header>
  <MasterFiles>
    <Customer>...</Customer>
    <Product>...</Product>
    <TaxTable>...</TaxTable>
  </MasterFiles>
  <SourceDocuments>
    <SalesInvoices>...</SalesInvoices>
    <MovementOfGoods>...</MovementOfGoods>
    <WorkingDocuments>...</WorkingDocuments>
    <Payments>...</Payments>
  </SourceDocuments>
</AuditFile>

FR-3.5.3 Header Requirements

FieldDescriptionSource
TaxRegistrationNumberCompany NIFUser configuration
TaxAccountingBasisExport type (F/I/C/S/E/P)Export selection
CompanyNameLegal company nameUser configuration
SoftwareCertificateNumberAT certificateSystem configuration
ProductCompanyTaxIDSoftware producer NIFSystem constant
ProductIDSoftware nameSystem constant
ProductVersionSoftware versionSystem constant

FR-3.5.4 Export Types

CodeTypeContents
CContabilidadeAccounting entries
FFaturaçãoBilling documents only
IIntegradoBoth accounting and billing
SAutofaturaçãoSelf-billing documents
EFaturação e-Faturae-Fatura billing subset
PFaturação ParcialPartial billing period

FR-3.5.5 Export Filtering

The system SHALL support exports filtered by:

  • Date range (start date, end date)
  • Document type
  • Document series
  • Document status
  • Customer/supplier

3.6 AT Communication

FR-3.6.1 Communication Methods

The system SHALL support all three AT communication methods:

MethodProtocolUse Case
Real-time WebserviceSOAP/HTTPSImmediate transmission
SAF-T File UploadHTTPSBatch monthly submission
Manual Portal EntryHTTPSLow-volume fallback

FR-3.6.2 Webservice Integration

Endpoints:

  • Production: https://servicos.portaldasfinancas.gov.pt:400/fews/faturas
  • Test: https://servicos.portaldasfinancas.gov.pt:700/fews/faturas

Authentication:

  • Protocol: WS-Security Username Token Profile 1.1
  • Password encryption: AES-128
  • SSL Certificate: 2048-bit RSA (AT-signed)

Operations:

  • RegisterInvoice
  • RegisterInvoiceMulti (batch)
  • ConsultarOperacao (status check)

FR-3.6.3 Communication Status Tracking

The system SHALL track for each document:

  • Communication status (pending, sent, confirmed, error)
  • Submission timestamp
  • AT response code
  • Retry count
  • Error messages

FR-3.6.4 Communication Deadlines

ObligationDeadline
Monthly invoice communicationDay 5 of following month
Zero-invoice declarationDay 5 of following month
August submissionsLast day of August

The system SHALL provide deadline notifications and compliance dashboards.

3.7 User Management

FR-3.7.1 Authentication

  • The system SHALL require user authentication for all access
  • Minimum password requirements: 8 characters, mixed case, numbers
  • The system SHALL support session timeout (configurable, default 30 min)
  • The system SHALL log all authentication attempts

FR-3.7.2 Role-Based Access Control

RolePermissions
AdministratorFull system access, user management, configuration
AccountantAll documents, SAF-T export, reports
Invoicing UserCreate/view documents, limited reports
ViewerRead-only access to documents

FR-3.7.3 Audit Trail

The system SHALL log:

  • User ID for all operations
  • Timestamp (server time, synchronized)
  • Operation type (create, view, cancel, export)
  • Document affected
  • IP address
  • Before/after values for modifications

3.8 Data Management

FR-3.8.1 Data Immutability

  • The system SHALL NOT provide functionality to alter signed document data
  • The system SHALL NOT allow direct database modifications to fiscal fields
  • Any corrections SHALL require issuance of credit/debit notes

FR-3.8.2 Record Retention

  • Retention period: 10 years minimum
  • The system SHALL maintain document accessibility throughout retention
  • The system SHALL support data export for archival purposes
  • Backup copies SHALL be stored in separate location

FR-3.8.3 Backup Requirements

  • Automated daily backups
  • Point-in-time recovery capability
  • Encrypted backup storage
  • Backup verification procedures
  • Documented restore procedures

4. Non-Functional Requirements

4.1 Performance

MetricRequirement
Document creation< 2 seconds
Signature generation< 500 milliseconds
SAF-T export (10,000 docs)< 5 minutes
QR code generation< 200 milliseconds
Search response< 1 second
Concurrent usersMinimum 50

4.2 Availability

MetricRequirement
System uptime99.5%
Planned maintenance window< 4 hours/month
Recovery Time Objective (RTO)< 4 hours
Recovery Point Objective (RPO)< 1 hour

4.3 Security

NFR-4.3.1 Data Protection

  • All data at rest SHALL be encrypted (AES-256)
  • All data in transit SHALL use TLS 1.2 or higher
  • Private keys SHALL be stored in secure key management system
  • Database access SHALL require authentication

NFR-4.3.2 Access Security

  • Failed login lockout after 5 attempts
  • Password hashing using bcrypt or Argon2
  • Session tokens with secure generation
  • CSRF protection on all forms
  • Input validation and sanitization

NFR-4.3.3 Key Management

  • Private key access restricted to signing service
  • Key backup in secure, encrypted format
  • Key compromise procedures documented
  • Annual key security review

4.4 Scalability

  • Horizontal scaling capability for web tier
  • Database read replicas for reporting
  • Async processing for batch operations
  • Queue-based AT communication

4.5 Compliance

  • GDPR compliance for personal data handling
  • Data residency within EU
  • Right to data portability (SAF-T export)
  • Consent management for data processing

4.6 Localization

  • Primary language: Portuguese (Portugal)
  • Secondary language: English
  • Date format: DD-MM-YYYY display, YYYY-MM-DD internal
  • Currency: EUR with € symbol
  • Decimal separator: comma (,)
  • Thousands separator: period (.)

5. Technical Specifications

5.1 Cryptographic Implementation Details

5.1.1 Key Generation

Algorithm: RSA
Key Size: 1024 bits
Format: PEM (PKCS#8 for private, X.509 for public)

5.1.2 Signing Process Pseudocode

def generate_signature(document):
    message = construct_message(document)
    message_bytes = message.encode('utf-8')
    
    signature = rsa_sign(
        private_key,
        message_bytes,
        padding=PKCS1v15,
        hash_algorithm=SHA1
    )
    
    signature_b64 = base64_encode(signature)
    # Remove any line breaks
    signature_b64 = signature_b64.replace('\n', '')
    
    # Must be exactly 172 characters
    assert len(signature_b64) == 172
    
    return signature_b64

def construct_message(document):
    return ';'.join([
        document.date.strftime('%Y-%m-%d'),
        document.system_entry_date.strftime('%Y-%m-%dT%H:%M:%S'),
        document.full_number,  # e.g., "FT A/125"
        format_decimal(document.gross_total),
        document.previous_hash or ''
    ])

5.1.3 Hash Extraction for Print

def extract_print_hash(signature_b64):
    # Positions 1, 11, 21, 31 (1-indexed)
    chars = [
        signature_b64[0],   # Position 1
        signature_b64[10],  # Position 11
        signature_b64[20],  # Position 21
        signature_b64[30]   # Position 31
    ]
    return '-'.join(chars)

5.2 SAF-T XML Structure Examples

5.2.1 Header Example

<Header>
  <AuditFileVersion>1.04_01</AuditFileVersion>
  <CompanyID>500123456</CompanyID>
  <TaxRegistrationNumber>500123456</TaxRegistrationNumber>
  <TaxAccountingBasis>F</TaxAccountingBasis>
  <CompanyName>Example Company Lda</CompanyName>
  <CompanyAddress>
    <AddressDetail>Rua Example 123</AddressDetail>
    <City>Lisboa</City>
    <PostalCode>1000-001</PostalCode>
    <Country>PT</Country>
  </CompanyAddress>
  <FiscalYear>2024</FiscalYear>
  <StartDate>2024-01-01</StartDate>
  <EndDate>2024-12-31</EndDate>
  <CurrencyCode>EUR</CurrencyCode>
  <DateCreated>2024-12-23</DateCreated>
  <TaxEntity>Global</TaxEntity>
  <ProductCompanyTaxID>509999999</ProductCompanyTaxID>
  <SoftwareCertificateNumber>326</SoftwareCertificateNumber>
  <ProductID>InvoiceSoft</ProductID>
  <ProductVersion>2.1.0</ProductVersion>
</Header>

5.2.2 Invoice Example

<Invoice>
  <InvoiceNo>FT A/125</InvoiceNo>
  <ATCUD>AFY08799-125</ATCUD>
  <DocumentStatus>
    <InvoiceStatus>N</InvoiceStatus>
    <InvoiceStatusDate>2024-12-15T14:30:00</InvoiceStatusDate>
    <SourceID>user@example.com</SourceID>
    <SourceBilling>P</SourceBilling>
  </DocumentStatus>
  <Hash>aWqC...172_chars...Xy9=</Hash>
  <HashControl>1</HashControl>
  <Period>12</Period>
  <InvoiceDate>2024-12-15</InvoiceDate>
  <InvoiceType>FT</InvoiceType>
  <SpecialRegimes>
    <SelfBillingIndicator>0</SelfBillingIndicator>
    <CashVATSchemeIndicator>0</CashVATSchemeIndicator>
    <ThirdPartiesBillingIndicator>0</ThirdPartiesBillingIndicator>
  </SpecialRegimes>
  <SourceID>user@example.com</SourceID>
  <SystemEntryDate>2024-12-15T14:30:00</SystemEntryDate>
  <CustomerID>C001</CustomerID>
  <Line>
    <LineNumber>1</LineNumber>
    <ProductCode>PROD001</ProductCode>
    <ProductDescription>Product Example</ProductDescription>
    <Quantity>10</Quantity>
    <UnitOfMeasure>UN</UnitOfMeasure>
    <UnitPrice>100.00</UnitPrice>
    <TaxPointDate>2024-12-15</TaxPointDate>
    <Description>Product Example</Description>
    <CreditAmount>1000.00</CreditAmount>
    <Tax>
      <TaxType>IVA</TaxType>
      <TaxCountryRegion>PT</TaxCountryRegion>
      <TaxCode>NOR</TaxCode>
      <TaxPercentage>23</TaxPercentage>
    </Tax>
  </Line>
  <DocumentTotals>
    <TaxPayable>230.00</TaxPayable>
    <NetTotal>1000.00</NetTotal>
    <GrossTotal>1230.00</GrossTotal>
  </DocumentTotals>
</Invoice>

5.3 Webservice Integration

5.3.1 WSDL Location

Production: https://servicos.portaldasfinancas.gov.pt:400/fews/faturas?wsdl

5.3.2 WS-Security Header

<wsse:Security>
  <wsse:UsernameToken>
    <wsse:Username>509999999/1</wsse:Username>
    <wsse:Password Type="...#PasswordDigest">
      [AES-128 encrypted password]
    </wsse:Password>
    <wsse:Nonce>[Base64 nonce]</wsse:Nonce>
    <wsu:Created>[Timestamp]</wsu:Created>
  </wsse:UsernameToken>
</wsse:Security>

5.3.3 Error Handling

CodeDescriptionAction
0SuccessMark as communicated
1-99Validation errorsFix data, retry
100-199Authentication errorsCheck credentials
200-299System errorsRetry with backoff

6. User Interface Requirements

6.1 Dashboard

  • Overview of documents issued (daily, monthly, yearly)
  • Communication status summary
  • Upcoming deadlines
  • Quick access to common actions

6.2 Document Creation

  • Step-by-step invoice creation wizard
  • Customer quick-search and creation
  • Product catalog with pricing
  • Tax automatic calculation
  • Real-time preview
  • One-click signature and communication

6.3 Document List

  • Filterable document list
  • Search by number, customer, date, amount
  • Status indicators (communicated, pending, error)
  • Batch selection for operations
  • Export to PDF, Excel

6.4 SAF-T Management

  • Export wizard with date range selection
  • Validation before export
  • Direct submission to AT option
  • Export history and status

6.5 Reports

  • Sales by period
  • Tax summary
  • Customer statements
  • Communication audit log
  • Hash chain validation report

6.6 Settings

  • Company configuration
  • User management
  • Series management
  • AT credentials configuration
  • Backup management

7. Integration Requirements

7.1 API Availability

The system SHALL provide REST API for:

  • Document creation
  • Document retrieval
  • Customer/product management
  • SAF-T export trigger
  • Communication status check

7.2 Webhook Support

Notifications for:

  • Document created
  • Document communicated
  • Communication error
  • Deadline approaching

7.3 Import Capabilities

  • Customer import (CSV, Excel)
  • Product import (CSV, Excel)
  • Historical data migration tools

7.4 Export Capabilities

  • SAF-T (PT) 1.04_01
  • PDF documents
  • Excel reports
  • CSV data extracts

8. Testing Requirements

8.1 Cryptographic Testing

  • Signature generation accuracy (compare with AT test vectors)
  • Hash chain integrity verification
  • Key pair validation
  • Signature verification round-trip

8.2 SAF-T Validation

  • XSD schema validation
  • AT validation tool testing
  • Field completeness verification
  • Cross-reference integrity (customers, products)

8.3 Webservice Testing

  • Test environment connectivity
  • Authentication flow
  • Success path validation
  • Error handling for all error codes
  • Timeout and retry behavior

8.4 User Acceptance Testing

  • Document creation workflows
  • Cancellation procedures
  • Export and communication
  • Report accuracy
  • Edge cases (year boundary, series rollover)

8.5 Security Testing

  • Penetration testing
  • Authentication bypass attempts
  • SQL injection testing
  • XSS vulnerability scanning
  • Key security audit

9. Deployment Requirements

9.1 Infrastructure

ComponentRequirement
Web ServerLinux, Nginx/Apache
Application ServerAs per technology choice
DatabasePostgreSQL 14+ or MySQL 8+
Key StorageHSM or secure key vault
Backup StorageEncrypted, geographically separate

9.2 Environments

EnvironmentPurpose
DevelopmentFeature development
TestingQA and integration testing
StagingPre-production validation
ProductionLive system

9.3 Monitoring

  • Application performance monitoring
  • Error tracking and alerting
  • Database performance monitoring
  • Security event logging
  • AT communication monitoring

10. Documentation Requirements

10.1 Technical Documentation

  • Architecture documentation
  • API documentation (OpenAPI/Swagger)
  • Database schema documentation
  • Deployment runbook
  • Disaster recovery procedures

10.2 User Documentation

  • User manual
  • Quick start guide
  • FAQ document
  • Video tutorials

10.3 Certification Documentation

  • Technical specification for AT
  • Security controls description
  • Data dictionary
  • Test results documentation

11. Project Timeline

Phase 1: Foundation (Weeks 1-4)

  • Database design
  • Core entity models
  • Authentication system
  • Basic UI framework

Phase 2: Core Features (Weeks 5-10)

  • Document creation
  • Cryptographic implementation
  • Hash chain system
  • SAF-T export

Phase 3: AT Integration (Weeks 11-14)

  • ATCUD implementation
  • QR code generation
  • Webservice integration
  • Communication tracking

Phase 4: Testing & Certification (Weeks 15-18)

  • Internal testing
  • SAF-T validation
  • Security testing
  • AT certification submission

Phase 5: Launch Preparation (Weeks 19-20)

  • User documentation
  • Training materials
  • Production deployment
  • Go-live support

12. Risks and Mitigations

RiskImpactProbabilityMitigation
AT certification delayHighMediumEarly submission, documentation quality
Cryptographic implementation errorsCriticalMediumExternal audit, test vectors
Regulatory changesHighLowModular architecture, monitoring
Webservice integration issuesMediumMediumThorough testing, fallback procedures
Key compromiseCriticalLowHSM usage, incident response plan

13. Appendices

Appendix A: Glossary

TermDefinition
ATAutoridade Tributária e Aduaneira (Portuguese Tax Authority)
ATCUDCódigo Único de Documento (Unique Document Code)
NIFNúmero de Identificação Fiscal (Tax ID Number)
SAF-TStandard Audit File for Tax purposes
e-FaturaElectronic invoice communication portal

Appendix B: Reference Documents

  • Decreto-Lei 28/2019
  • Portaria 363/2010
  • Portaria 302/2016
  • Portaria 195/2020
  • Despacho 8632/2014
  • SAF-T (PT) XSD Schema v1.04_01
  • AT Webservice Technical Documentation

Appendix C: Contact Information

PurposeContact
Webservice technical supportasi-psws@at.gov.pt
Certification inquiriesdspcit-dpat@dgci.min-financas.pt
Foreign entity NIF requestsdsrc@dgci.min-financas.pt

Document History

VersionDateAuthorChanges
1.02024-12-23[Author]Initial draft

This document is based on Portuguese legislation and AT technical specifications current as of December 2024. Requirements may change with regulatory updates.

Related Documents