Watch
1
0
Fork
You've already forked Seyyed_arc
0
forked from hesabix/arc
Seyyed_arc/hesabixUI/hesabix_ui/lib/services/tax_settings_service.dart
Motamed ASA fa730b6ab0 feat(tax): add Motamed ASA as a tax submission provider
«معتمد آسا» becomes a third, optional sending method beside «ارسال مستقیم»
and «همراه فن‌آوا». It follows the Fanava provider pattern and reuses
tax_provider_credentials, business_tax_provider_accounts and
tax_settings.submission_provider: no new table and no migration. Direct and
Fanava behaviour is unchanged; the default stays moadian_direct.

Connection (informed consent):
- The tax settings page shows what is shared with Motamed ASA and why, with
  links to its terms and to https://asatsp.ir/privacy#partner-software, and
  asks for explicit consent; consent user and time are stored as for Fanava.
- The owner signs up on Motamed ASA's own page (tax-system one-time code);
  Hesabix collects no identity documents. The business API key is handed to
  Hesabix once, after the owner agrees there; a business that already has an
  ASA API v2 key can enter its client id/secret instead.
- The business private key and memory id are not needed: the trusted
  company signs and sends.

Sending (ASA TSP API v2, https://api-v2.asatsp.ir):
- original: POST /api/invoice/send with a stable internalId per document;
  a rejected or unsent invoice is edited in place (editInvoice);
- correction: editInvoice with confirmCorrection;
- cancellation: cancelInvoice; marked cancelled only once accepted;
- sales return: ins=4 whose Body is the rows remaining after the return
  (RC_IITP.IS_V7.9 table 1), read from the chain's accepted invoice;
- timeouts are reconciled by internalId and never re-sent blindly;
- ASA issues the tax id; Hesabix stores it from the answer.

Inquiry and the tax workspace:
- inquire_tax_status, the auto-inquiry loop and the workspace health check
  read Motamed ASA invoices from ASA (inquiryInternalIds).
- The کارپوشه status (buyer reaction) and the Article 6 status (عدول /
  عدم عدول) of the document's own invoice are kept and shown as two new
  workspace columns (tax_workspace_status, tax_article6_status). A buyer
  rejection is shown there and no longer marks a registered invoice failed.
- «پرداخت‌ها و ثبت در کارپوشه» on a sent Motamed ASA invoice opens its
  payment table: every row with its registration status, and new rows
  (method, date/time, amount with VAT, trace and terminal numbers)
  registered through ASA's registerPayment; locked rows stay read-only and a
  lost answer reads the rows back instead of sending them again.

Admin: «اتصال معتمد آسا» under system settings › external services holds
the partner client id/secret Motamed ASA issues for Hesabix.

Tests: tests/test_motamed_asa_{client,invoice_payload,provider_service}.py

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 02:01:02 +03:00

217 lines
7.7 KiB
Dart
Executable file

import 'package:dio/dio.dart';
import '../core/api_client.dart';
import '../models/tax_settings_model.dart';
class TaxSettingsService {
final ApiClient _apiClient;
TaxSettingsService({ApiClient? apiClient}) : _apiClient = apiClient ?? ApiClient();
Future<TaxSettingsModel> fetchSettings(int businessId) async {
try {
final response = await _apiClient.get<Map<String, dynamic>>(
'/tax-settings/business/$businessId',
);
final data = response.data?['data'];
if (data is Map<String, dynamic>) {
return TaxSettingsModel.fromJson(data);
}
return TaxSettingsModel(businessId: businessId);
} on DioException catch (e) {
throw _extractMessage(e, defaultMessage: 'خطا در دریافت تنظیمات سامانه مودیان');
}
}
Future<TaxSettingsModel> saveSettings({
required int businessId,
required TaxSettingsModel settings,
}) async {
try {
final response = await _apiClient.post<Map<String, dynamic>>(
'/tax-settings/business/$businessId',
data: settings.toPayload(),
);
final data = response.data?['data'];
if (data is Map<String, dynamic>) {
return TaxSettingsModel.fromJson(data);
}
return settings;
} on DioException catch (e) {
throw _extractMessage(e, defaultMessage: 'خطا در ذخیره تنظیمات سامانه مودیان');
}
}
Future<TaxGeneratedKeys> generateKeys({
required int businessId,
required String personType,
required String nationalId,
String? nameFa,
String? nameEn,
String? email,
}) async {
try {
final response = await _apiClient.post<Map<String, dynamic>>(
'/tax-settings/business/$businessId/generate-keys',
data: {
'person_type': personType,
'national_id': nationalId,
if (nameFa != null && nameFa.trim().isNotEmpty) 'name_fa': nameFa.trim(),
if (nameEn != null && nameEn.trim().isNotEmpty) 'name_en': nameEn.trim(),
if (email != null && email.trim().isNotEmpty) 'email': email.trim(),
},
);
final data = response.data?['data'];
if (data is Map<String, dynamic>) {
return TaxGeneratedKeys.fromJson(data);
}
throw Exception('پاسخ نامعتبر از سرور');
} on DioException catch (e) {
throw _extractMessage(e, defaultMessage: 'خطا در تولید کلید سامانه مودیان');
}
}
Future<TaxDataQualityReport> fetchDataQuality(int businessId) async {
try {
final response = await _apiClient.get<Map<String, dynamic>>(
'/tax-settings/business/$businessId/data-quality',
);
final data = response.data?['data'];
if (data is Map<String, dynamic>) {
return TaxDataQualityReport.fromJson(data);
}
throw Exception('پاسخ نامعتبر از سرور');
} on DioException catch (e) {
throw _extractMessage(e, defaultMessage: 'خطا در دریافت گزارش کیفیت داده');
}
}
Future<Map<String, dynamic>> testConnection(
int businessId, {
Map<String, dynamic>? formPayload,
}) async {
try {
final response = await _apiClient.post<Map<String, dynamic>>(
'/tax-settings/business/$businessId/test-connection',
data: formPayload ?? const <String, dynamic>{},
);
final data = response.data?['data'];
if (data is Map<String, dynamic>) {
return data;
}
throw Exception('پاسخ نامعتبر از سرور');
} on DioException catch (e) {
throw _extractMessage(e, defaultMessage: 'خطا در تست اتصال به سامانه مودیان');
}
}
Future<TaxSettingsModel> selectProvider({
required int businessId,
required String providerCode,
bool consent = false,
Map<String, dynamic>? enrollment,
String? economicCode,
}) async {
try {
final response = await _apiClient.post<Map<String, dynamic>>(
'/tax-settings/business/$businessId/provider',
data: {
'provider_code': providerCode,
'consent': consent,
if (enrollment != null) 'enrollment': enrollment,
if (economicCode != null && economicCode.isNotEmpty) 'economic_code': economicCode,
},
);
final data = response.data?['data'];
if (data is Map<String, dynamic>) {
return TaxSettingsModel.fromJson(data);
}
throw Exception('پاسخ نامعتبر از سرور');
} on DioException catch (e) {
throw _extractMessage(e, defaultMessage: 'تغییر روش ارسال مالیاتی ناموفق بود');
}
}
Future<Map<String, dynamic>> syncFanavaAccount(int businessId) async {
try {
final response = await _apiClient.post<Map<String, dynamic>>(
'/tax-settings/business/$businessId/fanava/sync',
);
final data = response.data?['data'];
if (data is Map<String, dynamic>) return data;
throw Exception('پاسخ نامعتبر از سرور');
} on DioException catch (e) {
throw _extractMessage(e, defaultMessage: 'بررسی اتصال فن‌آوا ناموفق بود');
}
}
Future<Map<String, dynamic>> syncMotamedAsaAccount(int businessId) async {
try {
final response = await _apiClient.post<Map<String, dynamic>>(
'/tax-settings/business/$businessId/motamed-asa/sync',
);
final data = response.data?['data'];
if (data is Map<String, dynamic>) return data;
throw Exception('پاسخ نامعتبر از سرور');
} on DioException catch (e) {
throw _extractMessage(e, defaultMessage: 'بررسی اتصال معتمد آسا ناموفق بود');
}
}
/// A fresh sign-up link on Motamed ASA, under `motamed_asa_onboarding.url`.
Future<Map<String, dynamic>> renewMotamedAsaLink(int businessId) async {
try {
final response = await _apiClient.post<Map<String, dynamic>>(
'/tax-settings/business/$businessId/motamed-asa/link',
);
final data = response.data?['data'];
if (data is Map<String, dynamic>) return data;
throw Exception('پاسخ نامعتبر از سرور');
} on DioException catch (e) {
throw _extractMessage(e, defaultMessage: 'دریافت لینک ثبت‌نام معتمد آسا ناموفق بود');
}
}
Future<Map<String, dynamic>> saveMotamedAsaCredentials({
required int businessId,
required String clientId,
required String clientSecret,
String? economicCode,
}) async {
try {
final response = await _apiClient.post<Map<String, dynamic>>(
'/tax-settings/business/$businessId/motamed-asa/credentials',
data: {
'client_id': clientId,
'client_secret': clientSecret,
'consent': true,
if (economicCode != null && economicCode.isNotEmpty) 'economic_code': economicCode,
},
);
final data = response.data?['data'];
if (data is Map<String, dynamic>) return data;
throw Exception('پاسخ نامعتبر از سرور');
} on DioException catch (e) {
throw _extractMessage(e, defaultMessage: 'ثبت کلید API معتمد آسا ناموفق بود');
}
}
Exception _extractMessage(DioException exception, {required String defaultMessage}) {
final data = exception.response?.data;
if (data is Map<String, dynamic>) {
final error = data['error'];
if (error is Map<String, dynamic>) {
final message = error['message']?.toString();
if (message != null && message.isNotEmpty) {
return Exception(message);
}
}
final message = data['message']?.toString();
if (message != null && message.isNotEmpty) {
return Exception(message);
}
}
return Exception(defaultMessage);
}
}