File size: 13,629 Bytes
cf14c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<?php

declare(strict_types=1);

namespace Presentation\RequestHandlers\Installation;

use Billing\Domain\Repositories\PlanRepositoryInterface;
use Doctrine\ORM\EntityManagerInterface;
use Easy\Container\Attributes\Inject;
use Easy\Http\Message\RequestMethod;
use Easy\Router\Attributes\Route;
use Presentation\Exceptions\UnprocessableEntityException;
use Presentation\Response\EmptyResponse;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Throwable;
use User\Domain\Repositories\UserRepositoryInterface;

#[Route(path: '/database/data', method: RequestMethod::POST)]
class DataApi extends InstallationApi implements
    RequestHandlerInterface
{
    public function __construct(
        private EntityManagerInterface $em,
        private PlanRepositoryInterface $planRepo,
        private UserRepositoryInterface $userRepo,

        #[Inject('config.dirs.root')]
        private string $rootDir,
    ) {
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        try {
            $this->migrateData($request);
        } catch (Throwable $th) {
            $path = $this->rootDir . '/.env';

            if (file_exists($path)) {
                unlink($path);
            }

            throw new UnprocessableEntityException($th->getMessage());
        }

        return new EmptyResponse();
    }


    private function migrateData(ServerRequestInterface $request): void
    {
        $em = $this->em;
        $sm = $this->em->getConnection()->createSchemaManager();
        $payload = $request->getParsedBody();
        $ratios = $payload->ratios;

        if ($sm->tablesExist(['category_bkp'])) {
            // Migrate category_bkp to category
            $em->getConnection()->executeStatement(
                "INSERT INTO category (id, title, created_at, updated_at) 
                SELECT id, title, created_at, updated_at FROM category_bkp"
            );
        }

        if ($sm->tablesExist(['option_bkp'])) {
            // Migrate option_bkp to category
            $em->getConnection()->executeStatement(
                "INSERT INTO `option` (id, `key`, `value`, created_at, updated_at) 
                SELECT id, `key`, `value`, created_at, updated_at FROM option_bkp"
            );
        }

        if ($sm->tablesExist(['preset_bkp'])) {
            // Migrate preset_bkp to category
            $em->getConnection()->executeStatement(
                "INSERT INTO preset (id, `type`, `status`, created_at, updated_at, title, description, template, category_id, image, color, is_locked) 
                SELECT  id, `type`, `status`, created_at, updated_at, title, description, template, category_id, image, color, is_locked FROM preset_bkp"
            );
        }

        if ($sm->tablesExist(['plan_bkp'])) {
            // Fetchh all plans
            $plans = $em->getConnection()->fetchAllAssociative(
                "SELECT * FROM plan_bkp"
            );

            foreach ($plans as $p) {
                $credit_count = 0;

                if ($p['token_credit_count'] === null) {
                    $credit_count = null;
                } else {
                    $credit_count = $p['token_credit_count'] * $ratios->token;
                }

                if ($p['image_credit_count'] === null || $credit_count === null) {
                    $credit_count = null;
                } else {
                    $credit_count += $p['image_credit_count'] * $ratios->image;
                }

                if ($p['audio_credit_count'] === null || $credit_count === null) {
                    $credit_count = null;
                } else {
                    $credit_count += $p['audio_credit_count'] * $ratios->audio;
                }

                $em->getConnection()->executeStatement(
                    "INSERT INTO plan (id, created_at, updated_at, billing_cycle, status, title,  description, price, superiority, is_featured, icon, feature_list, credit_count) 
                    VALUE (:id, :created_at, :updated_at, :billing_cycle, :status, :title, :description, :price, :superiority, :is_featured, :icon, :feature_list, :credit_count)",
                    [
                        'id' => $p['id'],
                        'created_at' => $p['created_at'],
                        'updated_at' => $p['updated_at'],
                        'billing_cycle' => $p['billing_cycle'],
                        'status' => $p['status'],
                        'title' => $p['title'],
                        'description' => $p['description'],
                        'price' => $p['price'],
                        'superiority' => $p['superiority'],
                        'is_featured' => $p['is_featured'],
                        'icon' => $p['icon'],
                        'feature_list' => $p['feature_list'],
                        'credit_count' => $credit_count
                    ]
                );
            }
        }

        /** @var PlanEntity */
        foreach ($this->planRepo as $plan) {
            $plan->getSnapshot();
        }
        $em->flush();

        $plan_snapshot_map = $em->getConnection()->fetchAllKeyValue(
            "SELECT id, snapshot_id FROM plan"
        );

        $user_subs_map = [];
        if ($sm->tablesExist(['user_bkp'])) {
            // Migrate user_bkp to user
            $em->getConnection()->executeStatement(
                "INSERT INTO user (id, created_at, updated_at, email, password_hash, first_name, last_name, language, role, status, recovery_token, is_email_verified, email_verification_token) 
                SELECT 
                    id, created_at, updated_at, email, password_hash, first_name, last_name, language, role, status, recovery_token, is_email_verified, email_verification_token
                FROM user_bkp"
            );

            $user_subs_map = $em->getConnection()->fetchAllKeyValue(
                "SELECT id, active_subscription_id FROM user_bkp"
            );
        }

        /** @var UserEntity */
        foreach ($this->userRepo as $user) {
            // Create default workspace for all users
            $user->postLoad();
        }

        $em->flush();

        $user_ws_map = $em->getConnection()->fetchAllKeyValue(
            "SELECT id, current_workspace_id FROM user"
        );

        // Migrate documents
        if ($sm->tablesExist(['document_bkp'])) {
            // Fetchh all plans
            $docs = $em->getConnection()->fetchAllAssociative(
                "SELECT * FROM document_bkp"
            );

            foreach ($docs as $p) {
                $em->getConnection()->executeStatement(
                    "INSERT INTO library_item (id, workspace_id, user_id, visibility, created_at, updated_at, request_params, model, discr, used_credit_count,  preset_id, title, content, output_file_id, input_file_id, voice_id) 
                    VALUE (
                        :id, 
                        :workspace_id, 
                        :user_id, 
                        :visibility, 
                        :created_at, 
                        :updated_at, 
                        :request_params, 
                        :model, 
                        :discr, 
                        :used_credit_count, 
                        :preset_id, 
                        :title, 
                        :content, 
                        :output_file_id, 
                        :input_file_id, 
                        :voice_id
                    )",
                    [
                        'id' => $p['id'],
                        'workspace_id' => $user_ws_map[$p['user_id']],
                        'user_id' => $p['user_id'],
                        'visibility' => 0,
                        'created_at' => $p['created_at'],
                        'updated_at' => $p['updated_at'],
                        'request_params' => "{}",
                        'model' => "gpt-3.5",
                        'discr' => 'document',
                        'used_credit_count' => 0,
                        'preset_id' => $p['preset_id'],
                        'title' => $p['title'],
                        'content' => $p['output'],
                        'output_file_id' => NULL,
                        'input_file_id' => NULL,
                        'voice_id' => NULL
                    ]
                );
            }
        }

        // Migrate user subscriptions (active subscriptions only)
        if ($sm->tablesExist(['subscription_bkp'])) {
            $subs = $em->getConnection()->fetchAllAssociative(
                "SELECT 
                subscription_bkp.*, 
                plan_bkp.billing_cycle, 
                plan_bkp.token_credit_count,
                plan_bkp.image_credit_count,
                plan_bkp.audio_credit_count
                FROM subscription_bkp LEFT JOIN plan_bkp ON subscription_bkp.plan_id = plan_bkp.id"
            );

            $user_credits = [];
            foreach ($subs as $sub) {
                if ($sub['billing_cycle'] == 'one-time') {
                    $left = $user_credits[$sub['user_id']] ?? 0;

                    if (is_null($sub['token_credit_count'])) {
                        $left = NULL;
                    } else {
                        $left = ($sub['token_credit_count'] - $sub['token_usage_count']) * $ratios->token;
                    }

                    if (is_null($left) || is_null($sub['image_credit_count'])) {
                        $left = NULL;
                    } else {
                        $left += ($sub['image_credit_count'] - $sub['image_usage_count']) * $ratios->image;
                    }

                    if (is_null($left) || is_null($sub['audio_credit_count'])) {
                        $left = NULL;
                    } else {
                        $left += ($sub['audio_credit_count'] - $sub['audio_usage_count']) * $ratios->audio;
                    }

                    $user_credits[$sub['user_id']] = $left;
                    continue;
                }

                $usage_count = 0;

                if ($sub['token_usage_count'] === null) {
                    $usage_count = null;
                } else {
                    $usage_count = $sub['token_usage_count'] * $ratios->token;
                }

                if ($sub['image_usage_count'] === null || $usage_count === null) {
                    $usage_count = null;
                } else {
                    $usage_count += $sub['image_usage_count'] * $ratios->image;
                }

                if ($sub['audio_usage_count'] === null || $usage_count === null) {
                    $usage_count = null;
                } else {
                    $usage_count += $sub['audio_usage_count'] * $ratios->audio;
                }

                $renew_date = $sub['reset_credits_at'];
                $end_date = $sub['expire_at'];

                if ($end_date || !$sub['status']) {
                    $renew_date = null;

                    if (!$end_date) {
                        $end_date = date('Y-m-d H:i:s');
                    }
                }

                $em->getConnection()->executeStatement(
                    "INSERT INTO subscription (id, workspace_id, plan_id, created_at, updated_at, trial_period_days, payment_gateway, external_id, order_id, canceled_at, cancel_at, ended_at, renew_at, usage_count) 
                    VALUE (
                        :id, 
                        :workspace_id, 
                        :plan_id, 
                        :created_at, 
                        :updated_at, 
                        :trial_period_days, 
                        :payment_gateway, 
                        :external_id, 
                        :order_id, 
                        :canceled_at, 
                        :cancel_at, 
                        :ended_at, 
                        :renew_at, 
                        :usage_count
                    )",
                    [
                        'id' => $sub['id'],
                        'workspace_id' => $user_ws_map[$sub['user_id']],
                        'plan_id' => $plan_snapshot_map[$sub['plan_id']],
                        'created_at' => $sub['created_at'],
                        'updated_at' => $sub['updated_at'],
                        'trial_period_days' => $sub['trial_period_days'],
                        'payment_gateway' => $sub['payment_gateway'],
                        'external_id' => $sub['external_id'],
                        'order_id' => NULL,
                        'canceled_at' => $end_date,
                        'cancel_at' => $end_date,
                        'ended_at' => $end_date,
                        'renew_at' => $renew_date,
                        'usage_count' => $usage_count
                    ]
                );
            }

            foreach ($user_subs_map as $user_id => $sub_id) {
                $em->getConnection()->executeStatement(
                    "UPDATE workspace SET subscription_id = :sub_id WHERE id = :id",
                    ['sub_id' => $sub_id, 'id' => $user_ws_map[$user_id]]
                );
            }

            foreach ($user_credits as $user_id => $count) {
                $em->getConnection()->executeStatement(
                    "UPDATE workspace SET credit_count = :amount WHERE id = :id",
                    ['amount' => $count, 'id' => $user_ws_map[$user_id]]
                );
            }
        }
    }
}