File size: 11,866 Bytes
69996c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aaf2f91
 
 
 
69996c8
aaf2f91
 
 
 
 
 
 
 
 
 
69996c8
 
aaf2f91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69996c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import json
import os
from datetime import datetime

# Gradio App for API Workflow Builder
# Visual page builder with drag-and-drop interface

def load_page_builder():
    """Load the main page builder HTML"""
    with open('index.html', 'r', encoding='utf-8') as f:
        return f.read()

def save_workflow(workflow_name, html_content, css_content):
    """Save workflow to JSON file"""
    if not workflow_name:
        return "❌ ワークフロー名を入力してください"
    
    workflows_dir = 'workflows'
    os.makedirs(workflows_dir, exist_ok=True)
    
    workflow_data = {
        'name': workflow_name,
        'html': html_content,
        'css': css_content,
        'created_at': datetime.now().isoformat(),
        'updated_at': datetime.now().isoformat()
    }
    
    filename = f"{workflows_dir}/{workflow_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
    
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(workflow_data, f, ensure_ascii=False, indent=2)
    
    return f"✅ ワークフロー保存完了: {filename}"

def load_workflows():
    """Load list of saved workflows"""
    workflows_dir = 'workflows'
    if not os.path.exists(workflows_dir):
        return []
    
    workflows = []
    for filename in os.listdir(workflows_dir):
        if filename.endswith('.json'):
            with open(f"{workflows_dir}/{filename}", 'r', encoding='utf-8') as f:
                data = json.load(f)
                workflows.append({
                    'filename': filename,
                    'name': data.get('name', 'Unknown'),
                    'created_at': data.get('created_at', 'Unknown')
                })
    
    return workflows

def export_html(workflow_name, html_content, css_content):
    """Export complete HTML file"""
    full_html = f"""<!DOCTYPE html>

<html lang="ja">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>{workflow_name}</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/css/bootstrap.min.css">

    <style>{css_content}</style>

</head>

<body>

    {html_content}

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

</body>

</html>"""
    
    output_dir = 'exports'
    os.makedirs(output_dir, exist_ok=True)
    
    filename = f"{output_dir}/{workflow_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
    
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(full_html)
    
    return filename

# Gradio Interface
with gr.Blocks(title="🚀 API Workflow Builder", theme=gr.themes.Soft()) as app:
    gr.Markdown("""

    # 🚀 API Workflow Builder

    

    Visual page builder with drag-and-drop interface powered by GrapeJS.

    Create API workflow screens without coding!

    

    ## ✨ Features

    - 📦 Drag & Drop page builder

    - 🔌 API integration blocks

    - 💾 Save workflows to JSON/Supabase

    - 📥 Export as HTML file

    - 🎨 Visual styling editor

    """)
    
    with gr.Tab("📝 Page Builder"):
        gr.Markdown("""

        ### Visual Editor

        

        **Note**: Due to Gradio limitations, the full GrapeJS editor works best when opened in a separate window.

        

        Click the button below to open the full editor in a new tab:

        """)
        
        gr.Markdown("""

        <a href="https://kenken999.github.io/api-workflow-builder/" target="_blank" 

           style="display:inline-block; padding:15px 30px; background:linear-gradient(135deg, #667eea 0%, #764ba2 100%); 

                  color:white; text-decoration:none; border-radius:8px; font-weight:bold; margin:20px 0;">

            🚀 Open Full Editor

        </a>

        """)
        
        gr.Markdown("""

        ### Alternative: Localhost Setup

        

        For full functionality with API integration, run locally:

        

        ```bash

        # Clone the repository

        git clone https://huggingface.co/spaces/kenken999/api-workflow-builder

        cd api-workflow-builder

        

        # Open index.html in your browser

        # Or serve with a local server:

        python -m http.server 8000

        # Then visit: http://localhost:8000/index.html

        ```

        

        ### 使い方

        1. 左サイドバーから要素をドラッグ&ドロップ

        2. 右サイドバーでスタイルをカスタマイズ

        3. ヘッダーの「保存」ボタンでSupabaseに保存

        4. 下の「エクスポート」タブからHTMLファイルをダウンロード

        """)
    
    with gr.Tab("💾 Workflows"):
        gr.Markdown("### 保存されたワークフロー")
        
        with gr.Row():
            workflow_name_input = gr.Textbox(
                label="ワークフロー名",
                placeholder="my-workflow"
            )
            save_btn = gr.Button("💾 保存", variant="primary")
        
        save_status = gr.Textbox(label="保存ステータス", interactive=False)
        
        gr.Markdown("### ワークフロー一覧")
        workflows_list = gr.JSON(label="保存済みワークフロー")
        
        refresh_btn = gr.Button("🔄 更新")
        
        # Event handlers
        refresh_btn.click(
            fn=lambda: load_workflows(),
            outputs=workflows_list
        )
    
    with gr.Tab("📥 Export"):
        gr.Markdown("### HTMLエクスポート")
        
        with gr.Row():
            export_name = gr.Textbox(
                label="ファイル名",
                placeholder="my-page"
            )
            html_input = gr.Textbox(
                label="HTML Content",
                placeholder="<div>...</div>",
                lines=5
            )
            css_input = gr.Textbox(
                label="CSS Content",
                placeholder=".class { ... }",
                lines=5
            )
        
        export_btn = gr.Button("📥 HTMLエクスポート", variant="primary")
        export_result = gr.File(label="ダウンロード")
        
        export_btn.click(
            fn=export_html,
            inputs=[export_name, html_input, css_input],
            outputs=export_result
        )
    
    with gr.Tab("⚙️ Settings"):
        gr.Markdown("### API設定")
        
        with gr.Row():
            with gr.Column():
                supabase_url = gr.Textbox(
                    label="Supabase URL",
                    value="https://rootomzbucovwdqsscqd.supabase.co"
                )
                supabase_key = gr.Textbox(
                    label="Supabase Anon Key",
                    value="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
                    type="password"
                )
            
            with gr.Column():
                api_base_url = gr.Textbox(
                    label="API Base URL",
                    value="https://your-api.com",
                    placeholder="https://api.example.com"
                )
                api_auth_type = gr.Dropdown(
                    label="認証タイプ",
                    choices=["None", "Bearer Token", "API Key", "Basic Auth"],
                    value="None"
                )
        
        save_config_btn = gr.Button("💾 設定保存", variant="primary")
        config_status = gr.Textbox(label="保存ステータス", interactive=False)
    
    with gr.Tab("📚 Documentation"):
        gr.Markdown("""

        ## 📖 ドキュメント

        

        ### 🎯 概要

        API Workflow Builderは、ドラッグ&ドロップでAPIワークフロー画面を作成できるノーコードツールです。

        

        ### 🚀 クイックスタート

        

        1. **Page Builderタブ**を開く

        2. 左サイドバーから要素をドラッグ

        3. キャンバスにドロップして配置

        4. スタイルをカスタマイズ

        5. 保存またはエクスポート

        

        ### 📦 利用可能なブロック

        

        #### Shop11 API カテゴリ

        - **地金チェック削除**: 商品IDで地金チェックを削除

        - **査定タイトル生成**: 商品IDから査定タイトルを生成

        - **メール送信**: メール通知を送信

        - **商品検索**: キーワードで商品を検索

        - **商品データテーブル**: 商品データを検索・表示

        - **顧客検索テーブル**: 顧客情報を検索・表示

        - **査定検索テーブル**: 査定データを検索・表示

        - **商品登録フォーム**: 新規商品を登録

        

        ### 🔌 API連携

        

        すべてのAPIブロックは自動的にSupabaseにログを保存します。

        

        ```javascript

        // API呼び出し例

        fetch('/api/your-endpoint', {

            method: 'POST',

            headers: { 'Content-Type': 'application/json' },

            body: JSON.stringify(data)

        })

        .then(res => res.json())

        .then(data => {

            // Supabaseログ保存

            saveApiLogToSupabase('API名', endpoint, request, response, 'success');

        });

        ```

        

        ### 💾 データ保存

        

        ページデータは以下の形式でSupabaseに保存されます:

        

        ```json

        {

            "name": "page-name",

            "html_content": "<div>...</div>",

            "css_content": ".class {...}",

            "components_json": {...},

            "created_at": "2026-02-23T...",

            "updated_at": "2026-02-23T..."

        }

        ```

        

        ### 🎨 カスタマイズ

        

        新しいブロックを追加するには:

        

        1. `index.html`の`blockManager.add()`に新しいブロックを登録

        2. `api-functions.js`にAPI呼び出し関数を追加

        3. イベントリスナーに`data-action`を登録

        

        ### 🔐 セキュリティ

        

        - Supabase RLSポリシーで行レベルセキュリティを設定

        - API Keyは環境変数で管理

        - CSRF Tokenを使用したAPI保護

        

        ### 📊 技術スタック

        

        - **Frontend**: GrapeJS, Bootstrap, jQuery

        - **Backend**: Gradio (Python)

        - **Database**: Supabase (PostgreSQL)

        - **Hosting**: Hugging Face Spaces

        

        ### 🐛 トラブルシューティング

        

        **ブロックがドラッグできない**

        - ブラウザのキャッシュをクリア

        - ページをリロード

        

        **APIエラー**

        - ネットワークタブでHTTPステータス確認

        - Supabase接続情報を確認

        

        **保存できない**

        - RLSポリシーを確認

        - ブラウザコンソールのエラーログをチェック

        

        ### 📝 ライセンス

        

        MIT License

        

        ### 👤 作者

        

        Created for visual API workflow automation.

        

        ### 🔗 リンク

        

        - [GitHub Repository](https://github.com/your-repo)

        - [Supabase Docs](https://supabase.com/docs)

        - [GrapeJS Docs](https://grapesjs.com/docs/)

        """)

# Launch app
if __name__ == "__main__":
    app.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_error=True
    )