-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshow_invoice.py
More file actions
977 lines (805 loc) · 39.7 KB
/
show_invoice.py
File metadata and controls
977 lines (805 loc) · 39.7 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
freee請求書API - 請求書確認スクリプト
エンドポイント: https://api.freee.co.jp/iv/invoices(freee請求書専用API)
"""
import os
import sys
import json
import webbrowser
from datetime import datetime, timedelta
from pathlib import Path
from urllib.parse import urlencode, quote
import requests
from dotenv import load_dotenv
import argparse
# .envファイルを読み込む
load_dotenv()
# 認証情報
CLIENT_ID = os.getenv('CLIENT_ID')
CLIENT_SECRET = os.getenv('CLIENT_SECRET')
# API エンドポイント
AUTH_URL = 'https://accounts.secure.freee.co.jp/public_api/authorize'
TOKEN_URL = 'https://accounts.secure.freee.co.jp/public_api/token'
API_BASE_URL = 'https://api.freee.co.jp'
# freee請求書API用のベースパス
INVOICE_API_BASE = '/iv' # freee請求書API
# トークンファイルのパス(スクリプトと同じディレクトリ)
SCRIPT_DIR = Path(__file__).resolve().parent
TOKEN_FILE = SCRIPT_DIR / 'freee_tokens_invoice.json'
class FreeeInvoiceAPI:
"""freee請求書API クライアント(freee請求書専用)"""
def __init__(self):
self.client_id = CLIENT_ID
self.client_secret = CLIENT_SECRET
self.access_token = None
self.refresh_token = None
self.company_id = None
self.tokens_loaded = False
if not self.client_id or not self.client_secret:
raise ValueError("CLIENT_IDとCLIENT_SECRETを.envファイルに設定してください。")
print("\n" + "="*60)
print("認証プロセス開始")
print("="*60)
# 既存のトークンを読み込む
self._load_tokens()
# トークンが無効な場合は再認証
if not self.tokens_loaded or not self._verify_token():
print("\n⚠️ トークンが無効です。再認証が必要です。")
self._authenticate()
# company_idが設定されていない場合のみ取得
if not self.company_id:
print("\n📋 company_idを取得しています...")
self._fetch_company_id()
else:
print(f"\n✓ 認証済みの事業所を使用: Company ID {self.company_id}")
print("\n✅ 認証プロセス完了")
print(f" Company ID: {self.company_id}")
print("="*60 + "\n")
def _load_tokens(self):
"""保存されたトークンを読み込む"""
if os.path.exists(TOKEN_FILE):
try:
with open(TOKEN_FILE, 'r') as f:
tokens = json.load(f)
self.access_token = tokens.get('access_token')
self.refresh_token = tokens.get('refresh_token')
self.company_id = tokens.get('company_id')
self.tokens_loaded = True
print(f"✓ 保存されたトークンを読み込みました ({TOKEN_FILE})")
if self.company_id:
print(f" Company ID: {self.company_id}")
except Exception as e:
print(f"⚠️ トークンの読み込みに失敗: {e}")
self.tokens_loaded = False
else:
print(f"ℹ️ トークンファイルが見つかりません ({TOKEN_FILE})")
def _save_tokens(self, token_data):
"""トークンをファイルに保存"""
with open(TOKEN_FILE, 'w') as f:
json.dump(token_data, f, indent=2)
print(f"✓ トークンを {TOKEN_FILE} に保存しました")
def _verify_token(self):
"""トークンの有効性を確認(freee会計APIで検証)"""
if not self.access_token:
print("⚠️ アクセストークンがありません")
return False
print("\n🔍 トークンの有効性を確認中...")
headers = {
'Authorization': f'Bearer {self.access_token}'
}
try:
# freee会計APIで事業所一覧を取得してトークンを検証
response = requests.get(
f'{API_BASE_URL}/api/1/companies',
headers=headers,
timeout=10
)
print(f" レスポンスコード: {response.status_code}")
if response.status_code == 200:
print("✓ トークンは有効です")
return True
elif response.status_code == 401:
print("⚠️ トークンの有効期限が切れています")
print(" リフレッシュトークンで更新を試みます...")
return self._refresh_access_token()
else:
print(f"❌ トークン検証エラー: {response.status_code}")
print(f" レスポンス: {response.text[:200]}")
return False
except Exception as e:
print(f"❌ トークン検証中にエラー: {e}")
return False
def _refresh_access_token(self):
"""リフレッシュトークンを使用してアクセストークンを更新"""
if not self.refresh_token:
print("❌ リフレッシュトークンがありません")
return False
print("\n🔄 アクセストークンを更新中...")
data = {
'grant_type': 'refresh_token',
'client_id': self.client_id,
'client_secret': self.client_secret,
'refresh_token': self.refresh_token
}
try:
response = requests.post(TOKEN_URL, data=data, timeout=10)
print(f" レスポンスコード: {response.status_code}")
if response.status_code == 200:
token_data = response.json()
self.access_token = token_data['access_token']
self.refresh_token = token_data['refresh_token']
if self.company_id:
token_data['company_id'] = self.company_id
self._save_tokens(token_data)
print("✓ アクセストークンを更新しました")
return True
else:
print(f"❌ トークン更新失敗: {response.status_code}")
print(f" レスポンス: {response.text[:200]}")
return False
except Exception as e:
print(f"❌ トークン更新中にエラー: {e}")
return False
def _authenticate(self):
"""OAuth認証フローを実行"""
print("\n" + "="*60)
print("OAuth認証を開始します")
print("="*60)
redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'
params = {
'response_type': 'code',
'client_id': self.client_id,
'redirect_uri': redirect_uri,
'prompt': 'select_company'
}
auth_url = f'{AUTH_URL}?{urlencode(params)}'
print("\n以下のURLをブラウザで開いて認証してください:")
print("-" * 60)
print(auth_url)
print("-" * 60)
try:
webbrowser.open(auth_url)
print("\n✓ ブラウザを開きました")
except:
print("\n⚠️ ブラウザを自動的に開けませんでした")
print("\n認証後、表示される認可コードを入力してください:")
auth_code = input("認可コード: ").strip()
if not auth_code:
print("❌ 認可コードが入力されていません")
sys.exit(1)
print(f"\n🔄 認可コードでトークンを取得中... (コード: {auth_code[:10]}...)")
data = {
'grant_type': 'authorization_code',
'client_id': self.client_id,
'client_secret': self.client_secret,
'code': auth_code,
'redirect_uri': redirect_uri
}
try:
response = requests.post(TOKEN_URL, data=data, timeout=10)
print(f" レスポンスコード: {response.status_code}")
if response.status_code == 200:
token_data = response.json()
self.access_token = token_data['access_token']
self.refresh_token = token_data['refresh_token']
self.company_id = token_data.get('company_id')
self._save_tokens(token_data)
print("✓ 認証に成功しました")
if self.company_id:
print(f" Company ID: {self.company_id}")
else:
print(f"❌ 認証失敗: {response.status_code}")
print(f" レスポンス: {response.text[:500]}")
sys.exit(1)
except Exception as e:
print(f"❌ 認証中にエラー: {e}")
sys.exit(1)
def _fetch_company_id(self):
"""事業所情報からcompany_idを取得して保存"""
companies = self.get_company_info()
if companies and len(companies) > 0:
if len(companies) > 1:
print(f"\n📋 {len(companies)}件の事業所が見つかりました:")
for i, company in enumerate(companies, 1):
print(f" {i}. {company.get('display_name')} (ID: {company.get('id')})")
print("\n💡 請求書が登録されている事業所を選択してください")
while True:
try:
choice = input(f"選択してください (1-{len(companies)}): ").strip()
idx = int(choice) - 1
if 0 <= idx < len(companies):
self.company_id = companies[idx].get('id')
print(f"\n✓ 選択した事業所: {companies[idx].get('display_name')}")
print(f" Company ID: {self.company_id}")
break
else:
print(f"⚠️ 1-{len(companies)}の範囲で入力してください")
except ValueError:
print("⚠️ 数字を入力してください")
else:
self.company_id = companies[0].get('id')
print(f"✓ company_idを取得しました: {self.company_id}")
print(f" 事業所名: {companies[0].get('display_name')}")
if os.path.exists(TOKEN_FILE):
try:
with open(TOKEN_FILE, 'r') as f:
tokens = json.load(f)
tokens['company_id'] = self.company_id
self._save_tokens(tokens)
except Exception as e:
print(f"⚠️ トークンファイルの更新に失敗: {e}")
else:
print("❌ company_idを取得できませんでした")
def _api_request(self, method, endpoint, use_invoice_api=False, **kwargs):
"""APIリクエストを実行
Args:
method: HTTPメソッド
endpoint: エンドポイントパス
use_invoice_api: True の場合、freee請求書API(/iv)を使用
"""
headers = {
'Authorization': f'Bearer {self.access_token}',
'Content-Type': 'application/json'
}
if 'headers' in kwargs:
headers.update(kwargs['headers'])
del kwargs['headers']
# freee請求書APIを使用する場合
if use_invoice_api:
url = f'{API_BASE_URL}{INVOICE_API_BASE}{endpoint}'
else:
url = f'{API_BASE_URL}{endpoint}'
print(f"\n📡 API リクエスト:")
print(f" Method: {method}")
print(f" URL: {url}")
if 'params' in kwargs:
print(f" Params: {kwargs['params']}")
try:
response = requests.request(
method,
url,
headers=headers,
timeout=30,
**kwargs
)
print(f" レスポンスコード: {response.status_code}")
if response.status_code == 401:
print("⚠️ トークンの有効期限が切れました。リフレッシュします...")
if self._refresh_access_token():
headers['Authorization'] = f'Bearer {self.access_token}'
response = requests.request(
method,
url,
headers=headers,
timeout=30,
**kwargs
)
print(f" 再試行後のレスポンスコード: {response.status_code}")
return response
except Exception as e:
print(f"❌ APIリクエスト中にエラー: {e}")
raise
def get_company_info(self):
"""事業所情報を取得(freee会計APIを使用)"""
print("\n🏢 事業所情報を取得中...")
response = self._api_request('GET', '/api/1/companies', use_invoice_api=False)
if response.status_code == 200:
companies = response.json()
company_list = companies.get('companies', [])
print(f"✓ {len(company_list)}件の事業所を取得しました")
for i, company in enumerate(company_list, 1):
print(f" {i}. {company.get('display_name')} (ID: {company.get('id')})")
return company_list
else:
print(f"❌ 事業所情報の取得に失敗: {response.status_code}")
print(f" レスポンス: {response.text[:500]}")
return []
def get_invoices(self, limit=100, start_date=None, end_date=None,
sending_status=None, payment_status=None):
"""請求書一覧を取得(freee請求書API)
Args:
limit: 取得件数(最大100)
start_date: 請求日の開始日(YYYY-MM-DD)
end_date: 請求日の終了日(YYYY-MM-DD)
sending_status: 送付ステータス(sent/unsent)
payment_status: 入金ステータス(settled/unsettled)
"""
if not self.company_id:
print("❌ company_idが設定されていません")
return []
print(f"\n📄 請求書一覧を取得中(freee請求書API)...")
print(f" Company ID: {self.company_id}")
print(f" 取得件数: {limit}")
if start_date:
print(f" 開始日: {start_date}")
if end_date:
print(f" 終了日: {end_date}")
if sending_status:
print(f" 送付ステータス: {sending_status}")
if payment_status:
print(f" 入金ステータス: {payment_status}")
params = {
'company_id': self.company_id,
'limit': min(limit, 100) # 最大100件
}
# freee請求書APIのパラメータ名に合わせる
if start_date:
params['start_billing_date'] = start_date
if end_date:
params['end_billing_date'] = end_date
if sending_status:
params['sending_status'] = sending_status
if payment_status:
params['payment_status'] = payment_status
# freee請求書API(/iv/invoices)を使用
response = self._api_request('GET', '/invoices', params=params, use_invoice_api=True)
if response.status_code == 200:
try:
content_type = response.headers.get('Content-Type', '')
if 'application/json' not in content_type:
print(f"⚠️ 予期しないContent-Type: {content_type}")
print(f" レスポンス(最初の500文字): {response.text[:500]}")
return []
data = response.json()
invoices = data.get('invoices', [])
print(f"✓ {len(invoices)}件の請求書を取得しました")
if invoices:
print("\n取得した請求書:")
for i, inv in enumerate(invoices, 1):
partner_name = inv.get('partner_name') or inv.get('partner_display_name', 'N/A')
print(f" {i}. {inv.get('invoice_number')} - "
f"{partner_name} - "
f"¥{inv.get('total_amount', 0):,.0f}")
return invoices
except json.JSONDecodeError as e:
print(f"❌ JSONデコードエラー: {e}")
print(f" レスポンステキスト(最初の1000文字): {response.text[:1000]}")
return []
else:
print(f"❌ 請求書一覧取得に失敗:")
print(f" ステータスコード: {response.status_code}")
print(f" レスポンス: {response.text[:1000]}")
if response.status_code == 400:
print("\n💡 考えられる原因:")
print(" - リクエストパラメータが不正")
print(" - 指定したcompany_idに対する権限がない")
elif response.status_code == 403:
print("\n💡 考えられる原因:")
print(" - freee請求書APIへのアクセス権限がない")
print(" - アプリの権限設定を確認してください")
print(" - https://app.secure.freee.co.jp/developers/applications")
elif response.status_code == 404:
print("\n💡 考えられる原因:")
print(" - freee請求書サービスが有効化されていない")
print(" - freee請求書への登録が必要です")
print(" - https://www.freee.co.jp/invoice/")
return []
def get_invoice_detail(self, invoice_id):
"""請求書の詳細を取得(freee請求書API)"""
if not self.company_id:
print("❌ company_idが設定されていません")
return None
print(f"\n📋 請求書詳細を取得中... (ID: {invoice_id})")
params = {'company_id': self.company_id}
response = self._api_request('GET', f'/invoices/{invoice_id}',
params=params, use_invoice_api=True)
if response.status_code == 200:
try:
invoice = response.json().get('invoice')
print(f"✓ 請求書詳細を取得しました: {invoice.get('invoice_number')}")
return invoice
except json.JSONDecodeError:
print(f"❌ JSONデコードエラー: {response.text[:500]}")
return None
else:
print(f"❌ 請求書詳細取得に失敗: {response.status_code}")
print(f" レスポンス: {response.text[:500]}")
return None
def get_sending_status_text(status):
"""送付ステータスを日本語に変換"""
status_map = {
'sent': '送付済み',
'unsent': '送付待ち'
}
return status_map.get(status, status or 'N/A')
def get_payment_status_text(status):
"""入金ステータスを日本語に変換"""
status_map = {
'settled': '入金済み',
'unsettled': '入金待ち'
}
return status_map.get(status, status or 'N/A')
def get_cancel_status_text(status):
"""取消ステータスを日本語に変換"""
status_map = {
'canceled': '取消済み',
'uncanceled': '有効'
}
return status_map.get(status, status or 'N/A')
def format_invoice_summary_table(invoices):
"""請求書一覧をMarkdownテーブル形式に整形"""
if not invoices:
return "請求書がありません。"
lines = []
lines.append("| No | 請求書番号 | 取引先 | 請求日 | 支払期限 | 送付 | 入金 | 合計金額 |")
lines.append("|:---:|:---|:---|:---:|:---:|:---:|:---:|---:|")
for i, invoice in enumerate(invoices, 1):
invoice_number = invoice.get('invoice_number', 'N/A')
partner_name = invoice.get('partner_name') or invoice.get('partner_display_name', 'N/A')
billing_date = invoice.get('billing_date', 'N/A')
payment_date = invoice.get('payment_date', 'N/A')
sending_status = get_sending_status_text(invoice.get('sending_status'))
payment_status = get_payment_status_text(invoice.get('payment_status'))
total_amount = invoice.get('total_amount', 0)
lines.append(f"| {i} | {invoice_number} | {partner_name} | {billing_date} | "
f"{payment_date} | {sending_status} | {payment_status} | ¥{total_amount:,.0f} |")
return "\n".join(lines)
def format_invoice_detail(invoice):
"""請求書詳細をMarkdown形式に整形"""
lines = []
lines.append("## 請求書詳細")
lines.append("")
lines.append("### 基本情報")
lines.append("")
lines.append(f"**請求書ID:** {invoice.get('id', 'N/A')}")
lines.append(f"**請求書番号:** {invoice.get('invoice_number', 'N/A')}")
lines.append(f"**送付ステータス:** {get_sending_status_text(invoice.get('sending_status'))}")
lines.append(f"**入金ステータス:** {get_payment_status_text(invoice.get('payment_status'))}")
lines.append(f"**取消ステータス:** {get_cancel_status_text(invoice.get('cancel_status'))}")
lines.append(f"**請求日:** {invoice.get('billing_date', 'N/A')}")
lines.append(f"**支払期限:** {invoice.get('payment_date', 'N/A')}")
lines.append(f"**件名:** {invoice.get('subject', 'N/A')}")
lines.append("")
lines.append("### 取引先情報")
lines.append("")
partner_name = invoice.get('partner_name') or invoice.get('partner_display_name', 'N/A')
lines.append(f"**取引先名:** {partner_name}")
lines.append(f"**取引先ID:** {invoice.get('partner_id', 'N/A')}")
if invoice.get('partner_code'):
lines.append(f"**取引先コード:** {invoice.get('partner_code')}")
lines.append("")
lines.append("### 金額情報")
lines.append("")
lines.append(f"**小計(税別):** ¥{invoice.get('amount_excluding_tax', 0):,.0f}")
lines.append(f"**消費税額:** ¥{invoice.get('amount_tax', 0):,.0f}")
lines.append(f"**税込金額:** ¥{invoice.get('amount_including_tax', 0):,.0f}")
if invoice.get('amount_withholding_tax'):
lines.append(f"**源泉所得税:** ¥{invoice.get('amount_withholding_tax', 0):,.0f}")
lines.append(f"**合計金額:** ¥{invoice.get('total_amount', 0):,.0f}")
if invoice.get('amount_brought_forward'):
lines.append(f"**繰越金額:** ¥{invoice.get('amount_brought_forward', 0):,.0f}")
lines.append("")
# 税率別内訳
if invoice.get('amount_including_tax_10') is not None:
lines.append("### 税率別内訳")
lines.append("")
lines.append("| 税率 | 税抜 | 消費税 | 税込 |")
lines.append("|:---:|---:|---:|---:|")
if invoice.get('amount_excluding_tax_10', 0) > 0:
lines.append(f"| 10% | ¥{invoice.get('amount_excluding_tax_10', 0):,.0f} | "
f"¥{invoice.get('amount_tax_10', 0):,.0f} | "
f"¥{invoice.get('amount_including_tax_10', 0):,.0f} |")
if invoice.get('amount_excluding_tax_8', 0) > 0:
lines.append(f"| 8% | ¥{invoice.get('amount_excluding_tax_8', 0):,.0f} | "
f"¥{invoice.get('amount_tax_8', 0):,.0f} | "
f"¥{invoice.get('amount_including_tax_8', 0):,.0f} |")
if invoice.get('amount_excluding_tax_8_reduced', 0) > 0:
lines.append(f"| 8%(軽減) | ¥{invoice.get('amount_excluding_tax_8_reduced', 0):,.0f} | "
f"¥{invoice.get('amount_tax_8_reduced', 0):,.0f} | "
f"¥{invoice.get('amount_including_tax_8_reduced', 0):,.0f} |")
if invoice.get('amount_excluding_tax_0', 0) > 0:
lines.append(f"| 0% | ¥{invoice.get('amount_excluding_tax_0', 0):,.0f} | "
f"¥{invoice.get('amount_tax_0', 0):,.0f} | "
f"¥{invoice.get('amount_including_tax_0', 0):,.0f} |")
lines.append("")
# 明細行
invoice_lines = invoice.get('lines', [])
if invoice_lines:
lines.append("### 請求明細")
lines.append("")
lines.append("| No | 項目 | 数量 | 単価 | 税率 | 金額(税別) |")
lines.append("|:---:|:---|---:|---:|:---:|---:|")
for i, line in enumerate(invoice_lines, 1):
if line.get('type') == 'text':
# テキスト行
lines.append(f"| {i} | {line.get('description', '')} | - | - | - | - |")
else:
# 品目行
description = line.get('description', 'N/A')
qty = line.get('quantity') if line.get('quantity') is not None else 0
unit_price = line.get('unit_price')
tax_rate = line.get('tax_rate') if line.get('tax_rate') is not None else 0
amount = line.get('amount_excluding_tax') if line.get('amount_excluding_tax') is not None else 0
# unit_priceの安全な変換
if unit_price is not None:
try:
unit_price_str = f"¥{float(unit_price):,.0f}"
except (ValueError, TypeError):
unit_price_str = str(unit_price)
else:
unit_price_str = "-"
# 軽減税率の表示
tax_rate_str = f"{tax_rate}%" if tax_rate else "0%"
if line.get('reduced_tax_rate'):
tax_rate_str += "(軽減)"
# 金額の安全な変換
try:
amount_str = f"¥{float(amount):,.0f}"
except (ValueError, TypeError):
amount_str = "-"
lines.append(f"| {i} | {description} | {qty} | {unit_price_str} | "
f"{tax_rate_str} | {amount_str} |")
lines.append("")
# 備考
if invoice.get('invoice_note'):
lines.append("### 備考")
lines.append("")
lines.append(invoice.get('invoice_note'))
lines.append("")
# 社内メモ
if invoice.get('memo'):
lines.append("### 社内メモ")
lines.append("")
lines.append(invoice.get('memo'))
lines.append("")
lines.append("---")
lines.append("")
return "\n".join(lines)
def format_statistics(invoices):
"""請求書の統計情報をMarkdown形式に整形"""
lines = []
lines.append("### 統計情報")
lines.append("")
if not invoices:
lines.append("請求書がありません。")
return "\n".join(lines)
# 送付ステータス別集計
sending_count = {}
sending_amount = {}
# 入金ステータス別集計
payment_count = {}
payment_amount = {}
for invoice in invoices:
sending_status = get_sending_status_text(invoice.get('sending_status'))
payment_status = get_payment_status_text(invoice.get('payment_status'))
amount = invoice.get('total_amount', 0)
sending_count[sending_status] = sending_count.get(sending_status, 0) + 1
sending_amount[sending_status] = sending_amount.get(sending_status, 0) + amount
payment_count[payment_status] = payment_count.get(payment_status, 0) + 1
payment_amount[payment_status] = payment_amount.get(payment_status, 0) + amount
lines.append(f"**総請求書数:** {len(invoices)}件")
lines.append("")
lines.append("#### 送付ステータス別集計")
lines.append("")
lines.append("| ステータス | 件数 | 合計金額 |")
lines.append("|:---|---:|---:|")
for status in sorted(sending_count.keys()):
count = sending_count[status]
amount = sending_amount[status]
lines.append(f"| {status} | {count}件 | ¥{amount:,.0f} |")
lines.append("")
lines.append("#### 入金ステータス別集計")
lines.append("")
lines.append("| ステータス | 件数 | 合計金額 |")
lines.append("|:---|---:|---:|")
for status in sorted(payment_count.keys()):
count = payment_count[status]
amount = payment_amount[status]
lines.append(f"| {status} | {count}件 | ¥{amount:,.0f} |")
lines.append("")
total_amount = sum(invoice.get('total_amount', 0) for invoice in invoices)
lines.append(f"**総合計金額:** ¥{total_amount:,.0f}")
lines.append("")
return "\n".join(lines)
def main():
"""メイン処理"""
parser = argparse.ArgumentParser(
description='freee請求書確認スクリプト(freee請求書API版)',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
使用例:
python show_invoice_iv.py # 通常実行
python show_invoice_iv.py --reauth # 再認証して実行
python show_invoice_iv.py -r # 再認証して実行(短縮形)
注意:
このスクリプトは「freee請求書」サービスのAPIを使用します。
freee会計の請求書機能とは異なります。
freee請求書への登録が必要です: https://www.freee.co.jp/invoice/
"""
)
parser.add_argument(
'--reauth', '-r',
action='store_true',
help='トークンを削除して再認証する'
)
args = parser.parse_args()
script_path = Path(__file__).resolve()
script_dir = script_path.parent
output_file = script_dir / f"{script_path.stem}.md"
print("\n" + "="*60)
print("freee請求書確認スクリプト(freee請求書API版)")
print("="*60)
print(f"実行時刻: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"出力ファイル: {output_file}")
print(f"使用API: freee請求書API(https://api.freee.co.jp/iv)")
print("="*60)
if args.reauth:
if os.path.exists(TOKEN_FILE):
print(f"\n🗑️ 再認証オプションが指定されました")
print(f" トークンファイルを削除しています...")
try:
os.remove(TOKEN_FILE)
print(f"✓ {TOKEN_FILE} を削除しました")
print("✓ 新しい認証プロセスを開始します\n")
except Exception as e:
print(f"⚠️ トークンファイルの削除に失敗: {e}")
else:
print(f"\nℹ️ トークンファイルが存在しません(削除不要)")
elif os.path.exists(TOKEN_FILE):
print(f"\n✓ 既存のトークンファイルが見つかりました: {TOKEN_FILE}")
print("\n以下を選択してください:")
print("1. 既存のトークンを使用する(通常)")
print("2. トークンを削除して再認証する(権限追加後の初回実行時)")
print("\n💡 ヒント: 次回から --reauth オプションで自動的に再認証できます")
print(" 例: python show_invoice_iv.py --reauth")
choice = input("\n選択してください (1-2, Enter=1): ").strip()
if choice == '2':
print(f"\n🗑️ トークンファイルを削除しています...")
try:
os.remove(TOKEN_FILE)
print(f"✓ {TOKEN_FILE} を削除しました")
print("✓ 新しい認証プロセスを開始します")
except Exception as e:
print(f"⚠️ トークンファイルの削除に失敗: {e}")
else:
print("\n✓ 既存のトークンを使用します")
else:
print(f"\nℹ️ トークンファイルが見つかりません")
print("✓ 新しい認証プロセスを開始します")
try:
api = FreeeInvoiceAPI()
companies = api.get_company_info()
if not companies:
print("\n❌ 事業所情報が取得できませんでした")
with open(output_file, 'w', encoding='utf-8') as f:
f.write("# 請求書確認結果\n\n")
f.write("**エラー:** 事業所情報が取得できませんでした。\n")
return
current_company = None
for company in companies:
if company.get('id') == api.company_id:
current_company = company
break
if current_company:
print(f"\n✅ 使用中の事業所: {current_company.get('display_name')} (ID: {api.company_id})")
else:
print(f"\n⚠️ 事業所が見つかりません (ID: {api.company_id})")
return
print("\n" + "="*60)
print("確認メニュー")
print("="*60)
print("1. すべての請求書を表示")
print("2. 送付ステータスで絞り込んで表示")
print("3. 入金ステータスで絞り込んで表示")
print("4. 期間で絞り込んで表示")
print("5. 最近の請求書を表示(10件)")
print("="*60)
choice = input("\n選択してください (1-5): ").strip()
invoices = []
filter_info = ""
if choice == '1':
invoices = api.get_invoices(limit=100)
filter_info = "すべての請求書"
elif choice == '2':
print("\n送付ステータスを選択してください:")
print("1. 送付待ち (unsent)")
print("2. 送付済み (sent)")
status_choice = input("\n選択してください (1-2): ").strip()
status_map = {
'1': 'unsent',
'2': 'sent'
}
status = status_map.get(status_choice)
if status:
invoices = api.get_invoices(limit=100, sending_status=status)
filter_info = f"送付ステータス: {get_sending_status_text(status)}"
else:
print("❌ 無効な選択です")
return
elif choice == '3':
print("\n入金ステータスを選択してください:")
print("1. 入金待ち (unsettled)")
print("2. 入金済み (settled)")
status_choice = input("\n選択してください (1-2): ").strip()
status_map = {
'1': 'unsettled',
'2': 'settled'
}
status = status_map.get(status_choice)
if status:
invoices = api.get_invoices(limit=100, payment_status=status)
filter_info = f"入金ステータス: {get_payment_status_text(status)}"
else:
print("❌ 無効な選択です")
return
elif choice == '4':
print("\n期間を指定してください:")
start_date = input("開始日 (YYYY-MM-DD): ").strip()
end_date = input("終了日 (YYYY-MM-DD): ").strip()
if start_date and end_date:
invoices = api.get_invoices(limit=100, start_date=start_date, end_date=end_date)
filter_info = f"期間: {start_date} ~ {end_date}"
else:
print("❌ 日付が正しく入力されていません")
return
elif choice == '5':
invoices = api.get_invoices(limit=10)
filter_info = "最近の請求書(10件)"
else:
print("❌ 無効な選択です")
return
print(f"\n" + "="*60)
print(f"取得結果: {len(invoices)}件の請求書")
print("="*60)
show_detail = False
if invoices and len(invoices) <= 5:
detail_choice = input("\n詳細情報も表示しますか? (y/n): ").strip().lower()
show_detail = (detail_choice == 'y')
print(f"\n📝 結果をファイルに出力中... ({output_file})")
with open(output_file, 'w', encoding='utf-8') as f:
f.write("# 請求書確認結果(freee請求書)\n\n")
f.write(f"**確認日時:** {datetime.now().strftime('%Y年%m月%d日 %H:%M:%S')}\n\n")
f.write(f"**事業所:** {current_company.get('display_name') if current_company else 'N/A'}\n\n")
f.write(f"**絞り込み条件:** {filter_info}\n\n")
f.write(f"**使用API:** freee請求書API\n\n")
f.write("---\n\n")
if invoices:
f.write(format_statistics(invoices))
f.write("\n")
f.write("## 請求書一覧\n\n")
f.write(format_invoice_summary_table(invoices))
f.write("\n\n")
if show_detail:
f.write("## 詳細情報\n\n")
for i, invoice in enumerate(invoices, 1):
f.write(f"### {i}. {invoice.get('invoice_number', 'N/A')}\n\n")
invoice_id = invoice.get('id')
if invoice_id:
detail = api.get_invoice_detail(invoice_id)
if detail:
f.write(format_invoice_detail(detail))
if i < len(invoices):
f.write("\n")
print("\n✅ 請求書の確認が完了しました!")
else:
f.write("## 結果\n\n")
f.write("指定された条件に一致する請求書はありませんでした。\n\n")
f.write("### 考えられる原因\n\n")
f.write("1. freee請求書に請求書が登録されていない\n")
f.write("2. freee請求書APIへのアクセス権限がない\n")
f.write("3. freee請求書サービスへの登録が完了していない\n\n")
f.write("**確認方法:**\n")
f.write("- freee請求書: https://invoice.freee.co.jp/\n")
f.write("- freee請求書への登録: https://www.freee.co.jp/invoice/\n")
f.write("- アプリ設定: https://app.secure.freee.co.jp/developers/applications\n")
print("\n⚠️ 該当する請求書が見つかりませんでした")
print(f"\n✅ 結果を {output_file} に出力しました")
print("\n" + "="*60)
print("処理完了")
print("="*60 + "\n")
except Exception as e:
print(f"\n❌ エラーが発生しました: {e}")
import traceback
traceback.print_exc()
with open(output_file, 'w', encoding='utf-8') as f:
f.write("# 請求書確認結果\n\n")
f.write("## ❌ エラーが発生しました\n\n")
f.write(f"```\n{str(e)}\n```\n\n")
f.write("### スタックトレース\n\n")
f.write(f"```\n{traceback.format_exc()}\n```\n")
print(f"\nエラー内容を {output_file} に出力しました")
sys.exit(1)
if __name__ == '__main__':
main()