notify-utils 0.0.1__py3-none-any.whl → 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
notify_utils/discount.py CHANGED
@@ -22,12 +22,15 @@ def calculate_discount_percentage(old_price: float, new_price: float) -> float:
22
22
  Raises:
23
23
  ValueError: Se algum preço for negativo ou preço antigo for zero
24
24
  """
25
+
26
+ if old_price == 0.0:
27
+ return 0.0
28
+
29
+
30
+
25
31
  if old_price < 0 or new_price < 0:
26
32
  raise ValueError("Preços não podem ser negativos")
27
33
 
28
- if old_price == 0:
29
- raise ValueError("Preço antigo não pode ser zero")
30
-
31
34
  discount = ((old_price - new_price) / old_price) * 100
32
35
  return round(discount, 2)
33
36
 
@@ -0,0 +1,241 @@
1
+ Metadata-Version: 2.4
2
+ Name: notify-utils
3
+ Version: 0.1.0
4
+ Summary: Biblioteca Python para parsing de preços de scraping, cálculo de descontos e análise estatística de histórico de preços.
5
+ Author-email: Naruto Uzumaki <naruto_uzumaki@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/jefersonAlbara/notify-utils
8
+ Project-URL: Repository, https://github.com/jefersonAlbara/notify-utils
9
+ Project-URL: Issues, https://github.com/jefersonAlbara/notify-utils/issues
10
+ Keywords: price-tracking,discount-calculator,web-scraping,e-commerce,price-history,discount-analysis,promotion-detection,statistics
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Classifier: Topic :: Office/Business :: Financial
18
+ Requires-Python: >=3.12
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: discord-webhook>=1.4.1
22
+ Dynamic: license-file
23
+
24
+ # notify-utils
25
+
26
+ [![Python Version](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/)
27
+ [![Version](https://img.shields.io/badge/version-0.1.0-green.svg)](https://github.com/jefersonAlbara/notify-utils)
28
+ [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
29
+
30
+ Biblioteca Python completa para análise de preços de e-commerce: parsing, validação, cálculo de descontos reais e detecção de promoções falsas através de análise estatística de histórico.
31
+
32
+ ## 🎯 Funcionalidades
33
+
34
+ - **Parser de Preços**: Normaliza strings de preços de diferentes formatos (BR, US)
35
+ - **Cálculo de Descontos Inteligente**: Detecta descontos reais vs anunciados usando histórico
36
+ - **Análise Estatística Avançada**: Média, mediana, tendências, volatilidade e confiança
37
+ - **Sistema de Validação de Preços**: Estratégias inteligentes para validar preços antes de adicionar ao histórico
38
+ - **Ajuste Automático de Período**: Garante inclusão de histórico mais recente
39
+ - **Filtro de Ruído**: Ignora dados voláteis recentes (scraping com erros)
40
+ - **Notificações Discord**: Envio de alertas de preço via webhook (opcional)
41
+
42
+ ## Instalação
43
+
44
+ ```bash
45
+ pip install notify-utils
46
+ ```
47
+
48
+ ## Uso Básico
49
+
50
+ ### Parsing de Preços
51
+
52
+ ```python
53
+ from notify_utils import parse_price
54
+
55
+ preco = parse_price("R$ 1.299,90") # → 1299.90
56
+ preco = parse_price("$1,299.90") # → 1299.90
57
+ ```
58
+
59
+ ### Cálculo de Desconto com Histórico
60
+
61
+ ```python
62
+ from notify_utils import Price, get_discount_info
63
+ from datetime import datetime, timedelta
64
+
65
+ # Histórico de preços
66
+ precos = [
67
+ Price(value=1299.90, date=datetime.now() - timedelta(days=60)),
68
+ Price(value=1199.90, date=datetime.now() - timedelta(days=30)),
69
+ ]
70
+
71
+ # Calcular desconto real baseado no histórico
72
+ info = get_discount_info(
73
+ current_price=899.90,
74
+ price_history=precos,
75
+ period_days=30
76
+ )
77
+
78
+ print(f"Desconto real: {info.discount_percentage:.2f}%")
79
+ print(f"É desconto real? {info.is_real_discount}")
80
+ ```
81
+
82
+ ### Análise de Tendência
83
+
84
+ ```python
85
+ from notify_utils import calculate_price_trend
86
+
87
+ trend = calculate_price_trend(precos, days=30)
88
+
89
+ print(f"Direção: {trend.direction}") # 'increasing', 'decreasing', 'stable'
90
+ print(f"Mudança: {trend.change_percentage:.2f}%")
91
+ print(f"Confiança: {trend.confidence}")
92
+ ```
93
+
94
+ ### Validação de Preços com Estratégias
95
+
96
+ ```python
97
+ from notify_utils import PriceHistory, Price, PriceAdditionStrategy, PriceAction
98
+
99
+ history = PriceHistory(product_id="PROD123", prices=precos)
100
+
101
+ # Estratégia SMART: aceita quedas imediatas, aumentos após 24h
102
+ novo_preco = Price(value=899.90, date=datetime.now())
103
+ result = history.add_price(
104
+ novo_preco,
105
+ strategy=PriceAdditionStrategy.SMART,
106
+ min_hours_for_increase=24
107
+ )
108
+
109
+ # Integração com banco de dados
110
+ if result.action == PriceAction.ADDED:
111
+ db.insert_price(product_id, result.affected_price)
112
+ print(f"✅ Preço adicionado: R$ {result.affected_price.value:.2f}")
113
+ elif result.action == PriceAction.REJECTED:
114
+ print(f"⏭️ Ignorado: {result.reason}")
115
+ ```
116
+
117
+ ### Ajuste Automático de Período e Filtro de Ruído
118
+
119
+ ```python
120
+ from notify_utils import get_discount_info
121
+
122
+ # Ajusta período automaticamente + ignora 3 dias mais recentes
123
+ info = get_discount_info(
124
+ current_price=899.90,
125
+ price_history=precos,
126
+ period_days=30,
127
+ auto_adjust_period=True, # Inclui histórico mais recente
128
+ skip_recent_days=3 # Ignora ruído de 0-2 dias
129
+ )
130
+
131
+ print(f"Período solicitado: {info.period_days} dias")
132
+ print(f"Período ajustado: {info.adjusted_period_days} dias")
133
+ print(f"Dias ignorados: {info.skip_recent_days}")
134
+ print(f"Amostras usadas: {info.samples_count}")
135
+ ```
136
+
137
+ ### Notificações Discord
138
+
139
+ ```python
140
+ from notify_utils import Product, DiscordEmbedBuilder
141
+
142
+ produto = Product(
143
+ product_id="PROD123",
144
+ name="Notebook Gamer",
145
+ url="https://loja.com/produto"
146
+ )
147
+
148
+ builder = DiscordEmbedBuilder()
149
+ embed = builder.build_embed(produto, info, precos)
150
+ # Enviar via webhook Discord
151
+ ```
152
+
153
+ ## 📊 Estratégias de Validação
154
+
155
+ A biblioteca oferece 4 estratégias para adicionar preços ao histórico:
156
+
157
+ | Estratégia | Comportamento | Uso Recomendado |
158
+ |------------|---------------|-----------------|
159
+ | `ALWAYS` | Sempre adiciona | Testes, coleta sem filtro |
160
+ | `ONLY_DECREASE` | Apenas quedas | Alertas de promoção |
161
+ | `SMART` ⭐ | Quedas imediatas + aumentos após tempo mínimo | **Produção (padrão)** |
162
+ | `UPDATE_ON_EQUAL` | Atualiza timestamp se preço igual | Rastreamento de estabilidade |
163
+
164
+ ## 🔧 Casos de Uso
165
+
166
+ ### 1. Sistema de Scraping com Validação
167
+ ```python
168
+ def processar_scraping(product_id: str, novo_valor: float):
169
+ prices_from_db = db.get_prices(product_id)
170
+ history = PriceHistory(product_id=product_id, prices=prices_from_db)
171
+
172
+ novo_preco = Price(value=novo_valor, date=datetime.now())
173
+ result = history.add_price(novo_preco, strategy=PriceAdditionStrategy.SMART)
174
+
175
+ if result.action == PriceAction.ADDED:
176
+ db.insert_price(product_id, result.affected_price)
177
+
178
+ # Notificar se queda >= 10%
179
+ if result.status.value == "decreased" and abs(result.percentage_difference) >= 10:
180
+ notifier.send_price_alert(product, discount_info, history.prices)
181
+ ```
182
+
183
+ ### 2. Detecção de Promoções Falsas
184
+ ```python
185
+ # Loja anuncia "De R$ 1.999 por R$ 899" (50% off!)
186
+ # Mas histórico mostra que preço real era R$ 1.299
187
+
188
+ info = get_discount_info(
189
+ current_price=899.90,
190
+ price_history=precos_historicos,
191
+ advertised_old_price=1999.90 # IGNORADO quando há histórico!
192
+ )
193
+
194
+ print(f"Desconto anunciado: 55%")
195
+ print(f"Desconto REAL: {info.discount_percentage:.2f}%") # ~31% (vs R$ 1.299)
196
+ print(f"Estratégia: {info.strategy}") # 'history' (priorizou histórico)
197
+ ```
198
+
199
+ ### 3. Análise de Melhor Momento para Comprar
200
+ ```python
201
+ trend = calculate_price_trend(precos, days=30)
202
+
203
+ if trend.is_decreasing() and trend.has_high_confidence():
204
+ print("✅ Tendência de queda com alta confiança - BOM momento!")
205
+ elif trend.is_increasing() and trend.is_accelerating:
206
+ print("⚠️ Preço subindo rápido - compre agora ou espere próxima promoção")
207
+ ```
208
+
209
+ ## 📚 Documentação Completa
210
+
211
+ Para mais detalhes e exemplos avançados, consulte:
212
+ - [CLAUDE.md](CLAUDE.md) - Documentação completa com arquitetura e exemplos
213
+ - [notify_utils/](notify_utils/) - Código fonte com docstrings detalhadas
214
+
215
+ ## 🛠️ Requisitos
216
+
217
+ - Python >= 3.12
218
+ - discord-webhook >= 1.4.1 (opcional, apenas para notificações)
219
+
220
+ ## 📝 Changelog
221
+
222
+ ### v0.1.0 (2026-02-03)
223
+ - ✨ Sistema de validação de preços com estratégias
224
+ - 📊 Ajuste automático de período histórico
225
+ - 🔇 Filtro de ruído de dados recentes
226
+ - 📈 Análise de tendências com volatilidade
227
+ - 🎯 Novos modelos tipados e enums
228
+
229
+ Veja o [changelog completo no CLAUDE.md](CLAUDE.md#changelog)
230
+
231
+ ## 📄 Licença
232
+
233
+ MIT - veja [LICENSE](LICENSE) para detalhes.
234
+
235
+ ## 👥 Contribuindo
236
+
237
+ Contribuições são bem-vindas! Abra issues ou pull requests no [repositório](https://github.com/jefersonAlbara/notify-utils).
238
+
239
+ ## ⭐ Agradecimentos
240
+
241
+ Desenvolvido para ajudar consumidores a identificar promoções reais vs falsas no e-commerce brasileiro.
@@ -1,5 +1,5 @@
1
1
  notify_utils/__init__.py,sha256=ebhDsS5auEWFGobvgDkUIQa3lTBT1Ykz6wUvEz1NF14,2034
2
- notify_utils/discount.py,sha256=tIjifk7OkQEcLCXaHeY7QIAQyy1f_6FF4srusHyfTHw,12975
2
+ notify_utils/discount.py,sha256=dkB433oaBtnRoWghzCpyHh9jKpB7hZGhU0co6pYU7uw,12938
3
3
  notify_utils/models.py,sha256=jRNZjVyXorMzA5sZUfU3M4IICzZhuOlmCOB793skuLo,19361
4
4
  notify_utils/parser.py,sha256=IgEnClPQAOiAftkIVgQelIlSwDQvIFGIROWhOTiICbI,3191
5
5
  notify_utils/statistics.py,sha256=-ggrNiF3LnC-SN6tgXrsijk9k2V8h1vP8GoXp-v5yZU,10390
@@ -7,8 +7,8 @@ notify_utils/validators.py,sha256=oa9fgTWVb1iKJmMgUpFGy8lMmMeggd9BvEkmeN5jOVc,23
7
7
  notify_utils/notifiers/__init__.py,sha256=sWDgtEYr7fSzWt7JcXnGnWW5GCFsvr9OfIJ_87IYOOQ,290
8
8
  notify_utils/notifiers/discord_notifier.py,sha256=05w7e4IrxMlB-HnqsLSrLn9La-yHqeG72jpTGWTo8Jc,3640
9
9
  notify_utils/notifiers/formatters.py,sha256=OH81_ibaUW5F9QezWxlZyUblYkO0SYAtuttFZPFNhdo,2928
10
- notify_utils-0.0.1.dist-info/licenses/LICENSE,sha256=EAGnUR97L4E41x_9rLn8R8tVXrJrWFRt4gbaWNpKg54,1071
11
- notify_utils-0.0.1.dist-info/METADATA,sha256=pm80DurbFJkj4ylu6sCMlLnIN_rtcnmutGPwCQvBjug,3986
12
- notify_utils-0.0.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
13
- notify_utils-0.0.1.dist-info/top_level.txt,sha256=FAuoT6qfsWZmQUxWC3kbB-5yLQONkFW-HWdfAwVXGGY,13
14
- notify_utils-0.0.1.dist-info/RECORD,,
10
+ notify_utils-0.1.0.dist-info/licenses/LICENSE,sha256=EAGnUR97L4E41x_9rLn8R8tVXrJrWFRt4gbaWNpKg54,1071
11
+ notify_utils-0.1.0.dist-info/METADATA,sha256=eOBQ9TEzIqwWKC8aaF5vmuTqoRBxEpWGof1WBzh3pak,8491
12
+ notify_utils-0.1.0.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
13
+ notify_utils-0.1.0.dist-info/top_level.txt,sha256=FAuoT6qfsWZmQUxWC3kbB-5yLQONkFW-HWdfAwVXGGY,13
14
+ notify_utils-0.1.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (80.9.0)
2
+ Generator: setuptools (80.10.2)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,133 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: notify-utils
3
- Version: 0.0.1
4
- Summary: Biblioteca Python para parsing de preços de scraping, cálculo de descontos e análise estatística de histórico de preços.
5
- Author-email: Naruto Uzumaki <naruto_uzumaki@gmail.com>
6
- License: MIT
7
- Project-URL: Homepage, https://github.com/jefersonAlbara/notify-utils
8
- Project-URL: Repository, https://github.com/jefersonAlbara/notify-utils
9
- Project-URL: Issues, https://github.com/jefersonAlbara/notify-utils/issues
10
- Keywords: price-tracking,discount-calculator,web-scraping,e-commerce,price-history,discount-analysis,promotion-detection,statistics
11
- Classifier: Development Status :: 4 - Beta
12
- Classifier: Intended Audience :: Developers
13
- Classifier: License :: OSI Approved :: MIT License
14
- Classifier: Programming Language :: Python :: 3
15
- Classifier: Programming Language :: Python :: 3.12
16
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
- Classifier: Topic :: Office/Business :: Financial
18
- Requires-Python: >=3.12
19
- Description-Content-Type: text/markdown
20
- License-File: LICENSE
21
- Requires-Dist: discord-webhook>=1.4.1
22
- Dynamic: license-file
23
-
24
- # notify-utils
25
-
26
- Biblioteca Python para parsing de preços de scraping, cálculo de descontos e análise estatística de histórico de preços.
27
-
28
- ## Funcionalidades
29
-
30
- - **Parser de Preços**: Normaliza strings de preços de diferentes formatos (BR, US)
31
- - **Cálculo de Descontos**: Detecta descontos reais vs anunciados usando histórico
32
- - **Análise Estatística**: Média, mediana, tendências e volatilidade de preços
33
- - **Validação de Preços**: Sistema inteligente para validar preços antes de adicionar ao histórico
34
- - **Notificações Discord**: Envio de alertas de preço via webhook (opcional)
35
-
36
- ## Instalação
37
-
38
- ```bash
39
- pip install notify-utils
40
- ```
41
-
42
- ## Uso Básico
43
-
44
- ### Parsing de Preços
45
-
46
- ```python
47
- from notify_utils import parse_price
48
-
49
- preco = parse_price("R$ 1.299,90") # → 1299.90
50
- preco = parse_price("$1,299.90") # → 1299.90
51
- ```
52
-
53
- ### Cálculo de Desconto com Histórico
54
-
55
- ```python
56
- from notify_utils import Price, get_discount_info
57
- from datetime import datetime, timedelta
58
-
59
- # Histórico de preços
60
- precos = [
61
- Price(value=1299.90, date=datetime.now() - timedelta(days=60)),
62
- Price(value=1199.90, date=datetime.now() - timedelta(days=30)),
63
- ]
64
-
65
- # Calcular desconto real baseado no histórico
66
- info = get_discount_info(
67
- current_price=899.90,
68
- price_history=precos,
69
- period_days=30
70
- )
71
-
72
- print(f"Desconto real: {info.discount_percentage:.2f}%")
73
- print(f"É desconto real? {info.is_real_discount}")
74
- ```
75
-
76
- ### Análise de Tendência
77
-
78
- ```python
79
- from notify_utils import calculate_price_trend
80
-
81
- trend = calculate_price_trend(precos, days=30)
82
-
83
- print(f"Direção: {trend.direction}") # 'increasing', 'decreasing', 'stable'
84
- print(f"Mudança: {trend.change_percentage:.2f}%")
85
- print(f"Confiança: {trend.confidence}")
86
- ```
87
-
88
- ### Validação de Preços
89
-
90
- ```python
91
- from notify_utils import PriceHistory, Price, PriceAdditionStrategy
92
-
93
- history = PriceHistory(product_id="PROD123", prices=precos)
94
-
95
- # Validar antes de adicionar
96
- novo_preco = Price(value=899.90, date=datetime.now())
97
- result = history.add_price(
98
- novo_preco,
99
- strategy=PriceAdditionStrategy.SMART
100
- )
101
-
102
- if result.action.value == "added":
103
- print(f"Preço adicionado: R$ {result.affected_price.value:.2f}")
104
- ```
105
-
106
- ### Notificações Discord
107
-
108
- ```python
109
- from notify_utils import Product, DiscordEmbedBuilder
110
-
111
- produto = Product(
112
- product_id="PROD123",
113
- name="Notebook Gamer",
114
- url="https://loja.com/produto"
115
- )
116
-
117
- builder = DiscordEmbedBuilder()
118
- embed = builder.build_embed(produto, info, precos)
119
- # Enviar via webhook Discord
120
- ```
121
-
122
- ## Documentação Completa
123
-
124
- Para mais detalhes, consulte o arquivo [CLAUDE.md](CLAUDE.md) na raiz do projeto.
125
-
126
- ## Requisitos
127
-
128
- - Python >= 3.12
129
- - discord-webhook >= 1.4.1 (opcional, apenas para notificações)
130
-
131
- ## Licença
132
-
133
- MIT