scene_split_processor.py
145 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
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
场景拆分处理器 - 第1-13步的核心处理逻辑
"""
import logging
from datetime import datetime
from scene_type_mapping import (
SCENE_TYPE_MAPPING,
SCENE_TYPE_0_SPLIT,
DATA_MIGRATION_USER,
get_base_scene_code,
need_split,
get_copy_codes
)
class SceneSplitProcessor:
"""场景拆分处理器"""
def __init__(self, db_helper, id_mapping_manager, test_mode=False):
"""
初始化处理器
Args:
db_helper: 数据库辅助实例
id_mapping_manager: ID映射管理器实例
test_mode: 是否为测试模式,测试模式下每个scene_type只处理一条数据
"""
self.db = db_helper
self.id_mapper = id_mapping_manager
self.test_mode = test_mode
self.logger = logging.getLogger(__name__)
def step1_process_settle_account_rule(self):
"""
第1步:处理财务账户规则主表(表1)
dj_car_life_merchant_settle_account_rule
"""
self.logger.info("=" * 80)
self.logger.info("第1步:开始处理财务账户规则主表")
table_name = 'dj_car_life_merchant_settle_account_rule'
# 1. 处理 scene_type != 0 的记录,直接更新
self.logger.info("处理 scene_type != 0 的记录...")
for scene_type, base_scene_code in SCENE_TYPE_MAPPING.items():
if self.test_mode:
# 测试模式:每个 scene_type 只更新一条
update_sql = f"""
UPDATE {table_name}
SET base_scene_code = '{base_scene_code}',
updated_by = '{DATA_MIGRATION_USER}',
updated_date = NOW()
WHERE id = (
SELECT id FROM (
SELECT id FROM {table_name}
WHERE scene_type = {scene_type}
AND (base_scene_code IS NULL OR base_scene_code = '')
ORDER BY id DESC
LIMIT 1
) tmp
);
"""
self.logger.info(f" [测试模式] scene_type={scene_type} 只更新最新一条为 base_scene_code={base_scene_code}")
else:
# 正常模式:更新所有记录
update_sql = f"""
UPDATE {table_name}
SET base_scene_code = '{base_scene_code}',
updated_by = '{DATA_MIGRATION_USER}',
updated_date = NOW()
WHERE
scene_type = {scene_type} and merchant_id = 44210895
AND (base_scene_code IS NULL OR base_scene_code = '');
"""
if self.db.execute_update(update_sql):
self.logger.info(f" scene_type={scene_type} 更新为 base_scene_code={base_scene_code}")
# 2. 处理 scene_type = 0 的记录
self.logger.info("处理 scene_type = 0 的记录...")
# 2.1 查询所有需要拆分的记录
if self.test_mode:
# 测试模式:只取ID最大的一条
query_sql = f"""
SELECT id, source, merchant_id, scene_type, enable_flag, submit_flag,
created_by, created_date, updated_by, updated_date
FROM {table_name}
WHERE scene_type = 0
AND (base_scene_code IS NULL OR base_scene_code = '')
ORDER BY id DESC
LIMIT 1;
"""
self.logger.info(" [测试模式] 只处理 scene_type=0 的最新一条记录")
else:
# 正常模式:查询所有记录
query_sql = f"""
SELECT id, source, merchant_id, scene_type, enable_flag, submit_flag,
created_by, created_date, updated_by, updated_date, deleted_flag
FROM {table_name}
WHERE scene_type = 0 AND (base_scene_code IS NULL OR base_scene_code = '') and merchant_id = 44210895;
"""
records = self.db.execute_query(query_sql)
self.logger.info(f" 找到 {len(records)} 条需要拆分的记录")
# 2.2 更新原记录为第一个 base_scene_code
first_code = SCENE_TYPE_0_SPLIT[0]
if self.test_mode and len(records) > 0:
# 测试模式:只更新查询出来的那一条记录
record_id = records[0][0]
update_sql = f"""
UPDATE {table_name}
SET base_scene_code = '{first_code}',
updated_by = '{DATA_MIGRATION_USER}',
updated_date = NOW()
WHERE id = {record_id};
"""
else:
# 正常模式:更新所有记录
update_sql = f"""
UPDATE {table_name}
SET base_scene_code = '{first_code}',
updated_by = '{DATA_MIGRATION_USER}',
updated_date = NOW()
WHERE
scene_type = 0 and merchant_id = 44210895
AND (base_scene_code IS NULL OR base_scene_code = '');
"""
self.logger.info(f" 执行更新SQL: {update_sql.strip()}")
if self.db.execute_update(update_sql):
self.logger.info(f" 原记录已更新为 base_scene_code={first_code}")
# 2.3 批量复制插入3条新记录
copy_codes = SCENE_TYPE_0_SPLIT[1:] # 后3个
# 收集所有需要插入的数据
insert_batch = []
for record in records:
old_id = record[0]
source = record[1] if record[1] is not None else 'NULL'
merchant_id = record[2]
scene_type = record[3]
enable_flag = f"'{record[4]}'" if record[4] is not None else 'NULL'
submit_flag = f"'{record[5]}'" if record[5] is not None else 'NULL'
created_date = record[7] # 保存原记录的 created_date
deleted_flag = f"'{record[10]}'" if record[10] is not None else "'N'"
# 处理 created_date 格式
if created_date is None:
self.logger.warning(f" 记录 id={old_id} 的 created_date 为 NULL,跳过复制")
continue
elif isinstance(created_date, str):
created_date_str = created_date
else:
# datetime 对象转字符串
created_date_str = created_date.strftime('%Y-%m-%d %H:%M:%S')
for new_code in copy_codes:
insert_batch.append({
'old_id': old_id,
'source': source,
'merchant_id': merchant_id,
'scene_type': scene_type,
'base_scene_code': new_code,
'enable_flag': enable_flag,
'submit_flag': submit_flag,
'created_date_str': created_date_str,
'deleted_flag': deleted_flag
})
total_count = len(insert_batch)
self.logger.info(f" 收集到 {total_count} 条需要插入的记录")
if total_count > 0:
# 批量插入(10000条/批)
batch_size = 10000
total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量插入,共 {total_batches} 个批次,每批 {batch_size} 条")
copy_count = 0
for batch_idx in range(total_batches):
start_idx = batch_idx * batch_size
end_idx = min(start_idx + batch_size, total_count)
batch = insert_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建批量插入SQL
values = []
for item in batch:
values.append(
f"({item['source']}, {item['merchant_id']}, {item['scene_type']}, '{item['base_scene_code']}', "
f"{item['enable_flag']}, {item['submit_flag']}, "
f"'{DATA_MIGRATION_USER}', '{item['created_date_str']}', '{DATA_MIGRATION_USER}', NOW(), {item['deleted_flag']})"
)
insert_sql = f"""
INSERT INTO {table_name}
(source, merchant_id, scene_type, base_scene_code, enable_flag, submit_flag,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES {','.join(values)};
"""
if self.db.execute_update(insert_sql):
# 获取起始ID
first_new_id = self.db.execute_query_one("SELECT LAST_INSERT_ID();")[0]
# 建立映射
for i, item in enumerate(batch):
new_id = first_new_id + i
self.id_mapper.add_mapping(table_name, item['old_id'], new_id, item['base_scene_code'], item['merchant_id'])
copy_count += 1
self.logger.info(f" 批次 {batch_num}/{total_batches} 插入完成,本批 {len(batch)} 条,累计 {copy_count} 条")
# 记录原记录的映射关系(原记录ID映射到自己,但base_scene_code是第一个)
for record in records:
old_id = record[0]
merchant_id = record[2]
self.id_mapper.add_mapping(table_name, old_id, old_id, first_code, merchant_id)
mapping_count = self.id_mapper.get_mapping_count(table_name)
self.logger.info(f"第1步完成,共生成 {mapping_count} 条ID映射记录")
def step2_process_division_rule(self):
"""
第2步:处理分账规则主表(表6)
dj_car_life_merchant_division_rule
"""
self.logger.info("=" * 80)
self.logger.info("第2步:开始处理分账规则主表")
table_name = 'dj_car_life_merchant_division_rule'
# 1. 处理 scene_type != 0 的记录
self.logger.info("处理 scene_type != 0 的记录...")
for scene_type, base_scene_code in SCENE_TYPE_MAPPING.items():
if self.test_mode:
# 测试模式:每个 scene_type 只更新一条
update_sql = f"""
UPDATE {table_name}
SET base_scene_code = '{base_scene_code}',
updated_by = '{DATA_MIGRATION_USER}',
updated_date = NOW()
WHERE id = (
SELECT id FROM (
SELECT id FROM {table_name}
WHERE scene_type = {scene_type}
AND (base_scene_code IS NULL OR base_scene_code = '')
ORDER BY id DESC
LIMIT 1
) tmp
);
"""
self.logger.info(f" [测试模式] scene_type={scene_type} 只更新最新一条为 base_scene_code={base_scene_code}")
else:
# 正常模式:更新所有记录
update_sql = f"""
UPDATE {table_name}
SET base_scene_code = '{base_scene_code}',
updated_by = '{DATA_MIGRATION_USER}',
updated_date = NOW()
WHERE scene_type = {scene_type} and merchant_id = 44210895
AND (base_scene_code IS NULL OR base_scene_code = '');
"""
if self.db.execute_update(update_sql):
self.logger.info(f" scene_type={scene_type} 更新为 base_scene_code={base_scene_code}")
# 2. 处理 scene_type = 0 的记录
self.logger.info("处理 scene_type = 0 的记录...")
# 2.1 查询所有需要拆分的记录
if self.test_mode:
# 测试模式:只取ID最大的一条
query_sql = f"""
SELECT id, source, merchant_id, scene_type, enable_flag, submit_flag, division_type,
reality_platform_merchant_id, reality_platform_merchant_name, reality_platform_user_type,
multi_platform_merchant_flag, djzhy_sub_merchant_id, djzhy_sub_merchant_name,
reality_shop_merchant_id, reality_shop_merchant_name, reality_shop_user_type, reality_shop_level,
rule_audit_id, created_by, created_date, updated_by, updated_date
FROM {table_name}
WHERE scene_type = 0
AND (base_scene_code IS NULL OR base_scene_code = '')
ORDER BY id DESC
LIMIT 1;
"""
self.logger.info(" [测试模式] 只处理 scene_type=0 的最新一条记录")
else:
# 正常模式:查询所有记录
query_sql = f"""
SELECT id, source, merchant_id, scene_type, enable_flag, submit_flag, division_type,
reality_platform_merchant_id, reality_platform_merchant_name, reality_platform_user_type,
multi_platform_merchant_flag, djzhy_sub_merchant_id, djzhy_sub_merchant_name,
reality_shop_merchant_id, reality_shop_merchant_name, reality_shop_user_type, reality_shop_level,
rule_audit_id, created_by, created_date, updated_by, updated_date, deleted_flag
FROM {table_name}
WHERE scene_type = 0 and merchant_id = 44210895
AND (base_scene_code IS NULL OR base_scene_code = '');
"""
records = self.db.execute_query(query_sql)
self.logger.info(f" 找到 {len(records)} 条需要拆分的记录")
# 2.2 更新原记录
first_code = SCENE_TYPE_0_SPLIT[0]
if self.test_mode and len(records) > 0:
# 测试模式:只更新查询出来的那一条记录
record_id = records[0][0]
update_sql = f"""
UPDATE {table_name}
SET base_scene_code = '{first_code}',
updated_by = '{DATA_MIGRATION_USER}',
updated_date = NOW()
WHERE id = {record_id};
"""
else:
# 正常模式:更新所有记录
update_sql = f"""
UPDATE {table_name}
SET base_scene_code = '{first_code}',
updated_by = '{DATA_MIGRATION_USER}',
updated_date = NOW()
WHERE scene_type = 0 and merchant_id = 44210895
AND (base_scene_code IS NULL OR base_scene_code = '');
"""
if self.db.execute_update(update_sql):
self.logger.info(f" 原记录已更新为 base_scene_code={first_code}")
# 2.3 批量复制插入新记录
copy_codes = SCENE_TYPE_0_SPLIT[1:]
# 收集所有需要插入的数据
insert_batch = []
for record in records:
old_id = record[0]
source = record[1] if record[1] is not None else 'NULL'
merchant_id = record[2]
scene_type = record[3]
enable_flag = f"'{record[4]}'" if record[4] is not None else 'NULL'
submit_flag = f"'{record[5]}'" if record[5] is not None else 'NULL'
division_type = record[6] if record[6] is not None else 'NULL'
reality_platform_merchant_id = record[7] if record[7] is not None else 'NULL'
reality_platform_merchant_name = f"'{record[8]}'" if record[8] is not None else 'NULL'
reality_platform_user_type = record[9] if record[9] is not None else 'NULL'
multi_platform_merchant_flag = f"'{record[10]}'" if record[10] is not None else 'NULL'
djzhy_sub_merchant_id = record[11] if record[11] is not None else 'NULL'
djzhy_sub_merchant_name = f"'{record[12]}'" if record[12] is not None else 'NULL'
reality_shop_merchant_id = record[13] if record[13] is not None else 'NULL'
reality_shop_merchant_name = f"'{record[14]}'" if record[14] is not None else 'NULL'
reality_shop_user_type = record[15] if record[15] is not None else 'NULL'
reality_shop_level = record[16] if record[16] is not None else 'NULL'
rule_audit_id = record[17] if record[17] is not None else 'NULL'
created_date = record[19] # 保存原记录的 created_date
deleted_flag = f"'{record[22]}'" if record[22] is not None else "'N'"
# 处理 created_date 格式
if created_date is None:
self.logger.warning(f" 记录 id={old_id} 的 created_date 为 NULL,跳过复制")
continue
elif isinstance(created_date, str):
created_date_str = created_date
else:
# datetime 对象转字符串
created_date_str = created_date.strftime('%Y-%m-%d %H:%M:%S')
for new_code in copy_codes:
insert_batch.append({
'old_id': old_id,
'source': source,
'merchant_id': merchant_id,
'scene_type': scene_type,
'base_scene_code': new_code,
'enable_flag': enable_flag,
'submit_flag': submit_flag,
'division_type': division_type,
'reality_platform_merchant_id': reality_platform_merchant_id,
'reality_platform_merchant_name': reality_platform_merchant_name,
'reality_platform_user_type': reality_platform_user_type,
'multi_platform_merchant_flag': multi_platform_merchant_flag,
'djzhy_sub_merchant_id': djzhy_sub_merchant_id,
'djzhy_sub_merchant_name': djzhy_sub_merchant_name,
'reality_shop_merchant_id': reality_shop_merchant_id,
'reality_shop_merchant_name': reality_shop_merchant_name,
'reality_shop_user_type': reality_shop_user_type,
'reality_shop_level': reality_shop_level,
'rule_audit_id': rule_audit_id,
'created_date_str': created_date_str,
'deleted_flag': deleted_flag
})
total_count = len(insert_batch)
self.logger.info(f" 收集到 {total_count} 条需要插入的记录")
if total_count > 0:
# 批量插入(10000条/批)
batch_size = 10000
total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量插入,共 {total_batches} 个批次,每批 {batch_size} 条")
copy_count = 0
for batch_idx in range(total_batches):
start_idx = batch_idx * batch_size
end_idx = min(start_idx + batch_size, total_count)
batch = insert_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建批量插入SQL
values = []
for item in batch:
values.append(
f"({item['source']}, {item['merchant_id']}, {item['scene_type']}, '{item['base_scene_code']}', "
f"{item['enable_flag']}, {item['submit_flag']}, {item['division_type']}, "
f"{item['reality_platform_merchant_id']}, {item['reality_platform_merchant_name']}, {item['reality_platform_user_type']}, "
f"{item['multi_platform_merchant_flag']}, {item['djzhy_sub_merchant_id']}, {item['djzhy_sub_merchant_name']}, "
f"{item['reality_shop_merchant_id']}, {item['reality_shop_merchant_name']}, {item['reality_shop_user_type']}, {item['reality_shop_level']}, "
f"{item['rule_audit_id']}, '{DATA_MIGRATION_USER}', '{item['created_date_str']}', '{DATA_MIGRATION_USER}', NOW(), {item['deleted_flag']})"
)
insert_sql = f"""
INSERT INTO {table_name}
(source, merchant_id, scene_type, base_scene_code, enable_flag, submit_flag, division_type,
reality_platform_merchant_id, reality_platform_merchant_name, reality_platform_user_type,
multi_platform_merchant_flag, djzhy_sub_merchant_id, djzhy_sub_merchant_name,
reality_shop_merchant_id, reality_shop_merchant_name, reality_shop_user_type, reality_shop_level,
rule_audit_id, created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES {','.join(values)};
"""
if self.db.execute_update(insert_sql):
# 获取起始ID
first_new_id = self.db.execute_query_one("SELECT LAST_INSERT_ID();")[0]
# 建立映射
for i, item in enumerate(batch):
new_id = first_new_id + i
self.id_mapper.add_mapping(table_name, item['old_id'], new_id, item['base_scene_code'], item['merchant_id'])
copy_count += 1
self.logger.info(f" 批次 {batch_num}/{total_batches} 插入完成,本批 {len(batch)} 条,累计 {copy_count} 条")
# 记录原记录映射
for record in records:
old_id = record[0]
merchant_id = record[2]
self.id_mapper.add_mapping(table_name, old_id, old_id, first_code, merchant_id)
mapping_count = self.id_mapper.get_mapping_count(table_name)
self.logger.info(f"第2步完成,共生成 {mapping_count} 条ID映射记录")
def step3_process_settle_rule_group(self, merchant_id=None):
"""
第3步:处理结算规则分组表(表2)
dj_car_life_merchant_goods_type_group_settle_rule
优化:批量插入
Args:
merchant_id: 商户ID,必须提供
"""
if merchant_id is None:
raise ValueError("step3_process_settle_rule_group 必须提供 merchant_id 参数")
self.logger.info("=" * 80)
self.logger.info(f"第3步:开始处理结算规则分组表(商户ID: {merchant_id})")
table_name = 'dj_car_life_merchant_goods_type_group_settle_rule'
parent_table = 'dj_car_life_merchant_settle_account_rule'
# 查询表1的所有映射关系(排除原记录映射到自己的情况)
query_mapping_sql = f"""
SELECT DISTINCT old_id, new_id, base_scene_code, merchant_id
FROM tmp_rule_id_mapping
WHERE table_name = '{parent_table}'
AND old_id != new_id
AND merchant_id = {merchant_id}
ORDER BY merchant_id, old_id, new_id;
"""
mappings = self.db.execute_query(query_mapping_sql)
self.logger.info(f" 找到 {len(mappings)} 条表1的映射关系需要处理")
# 收集所有需要插入的数据
insert_batch = []
for mapping in mappings:
old_settle_id = mapping[0]
new_settle_id = mapping[1]
base_scene_code = mapping[2]
merchant_id = mapping[3]
# 查询原settle_rule_id对应的所有表2记录
query_sql = f"""
SELECT id, settle_rule_id, goods_type_group_id, group_type,
shop4s_deduct_charge_flag, partner_deduct_charge_flag,
goods_cost_flag, goods_cost_convert_rate,
virtual_account_cost_flag, virtual_account_cost_convert_rate,
recovery_cost_flag, recovery_cost_convert_rate,
dj_cost_flag, dj_cost_convert_rate,
third_party_cost_flag, third_party_cost_convert_rate
FROM {table_name}
WHERE settle_rule_id = {old_settle_id};
"""
records = self.db.execute_query(query_sql)
for record in records:
insert_batch.append({
'old_id': record[0],
'new_settle_id': new_settle_id,
'goods_type_group_id': record[2] if record[2] is not None else 'NULL',
'group_type': record[3],
'shop4s_deduct_charge_flag': record[4] if record[4] is not None else 'N',
'partner_deduct_charge_flag': record[5] if record[5] is not None else 'Y',
'goods_cost_flag': record[6],
'goods_cost_convert_rate': record[7],
'virtual_account_cost_flag': record[8],
'virtual_account_cost_convert_rate': record[9],
'recovery_cost_flag': record[10],
'recovery_cost_convert_rate': record[11],
'dj_cost_flag': record[12],
'dj_cost_convert_rate': record[13],
'third_party_cost_flag': record[14],
'third_party_cost_convert_rate': record[15],
'base_scene_code': base_scene_code,
'merchant_id': merchant_id
})
total_count = len(insert_batch)
self.logger.info(f" 收集到 {total_count} 条需要插入的记录")
if total_count == 0:
self.logger.info(f"第3步完成,没有需要处理的记录")
return
# 批量插入(10000条/批)
batch_size = 10000
total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量插入,共 {total_batches} 个批次,每批 {batch_size} 条")
copy_count = 0
for batch_idx in range(total_batches):
start_idx = batch_idx * batch_size
end_idx = min(start_idx + batch_size, total_count)
batch = insert_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建批量插入SQL
values = []
for item in batch:
values.append(
f"({item['new_settle_id']}, {item['goods_type_group_id']}, {item['group_type']}, "
f"'{item['shop4s_deduct_charge_flag']}', '{item['partner_deduct_charge_flag']}', "
f"'{item['goods_cost_flag']}', {item['goods_cost_convert_rate']}, "
f"'{item['virtual_account_cost_flag']}', {item['virtual_account_cost_convert_rate']}, "
f"'{item['recovery_cost_flag']}', {item['recovery_cost_convert_rate']}, "
f"'{item['dj_cost_flag']}', {item['dj_cost_convert_rate']}, "
f"'{item['third_party_cost_flag']}', {item['third_party_cost_convert_rate']}, "
f"'{DATA_MIGRATION_USER}', NOW(), '{DATA_MIGRATION_USER}', NOW(), 'N')"
)
insert_sql = f"""
INSERT INTO {table_name}
(settle_rule_id, goods_type_group_id, group_type,
shop4s_deduct_charge_flag, partner_deduct_charge_flag,
goods_cost_flag, goods_cost_convert_rate,
virtual_account_cost_flag, virtual_account_cost_convert_rate,
recovery_cost_flag, recovery_cost_convert_rate,
dj_cost_flag, dj_cost_convert_rate,
third_party_cost_flag, third_party_cost_convert_rate,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES {','.join(values)};
"""
if self.db.execute_update(insert_sql):
# 获取起始ID
first_new_id = self.db.execute_query_one("SELECT LAST_INSERT_ID();")[0]
# 建立映射
for i, item in enumerate(batch):
new_id = first_new_id + i
self.id_mapper.add_mapping(table_name, item['old_id'], new_id, item['base_scene_code'], item['merchant_id'])
copy_count += 1
self.logger.info(f" 批次 {batch_num}/{total_batches} 插入完成,本批 {len(batch)} 条,累计 {copy_count} 条")
self.logger.info(f"第3步完成,共复制 {copy_count} 条记录")
def step4_process_division_rule_group(self, merchant_id=None):
"""
第4步:处理分账规则分组表(表7)
dj_car_life_merchant_goods_type_group_division_rule
Args:
merchant_id: 商户ID,必须提供
"""
if merchant_id is None:
raise ValueError("step4_process_division_rule_group 必须提供 merchant_id 参数")
self.logger.info("=" * 80)
self.logger.info(f"第4步:开始处理分账规则分组表(商户ID: {merchant_id})")
table_name = 'dj_car_life_merchant_goods_type_group_division_rule'
parent_table = 'dj_car_life_merchant_division_rule'
# 查询表6的所有映射关系
query_mapping_sql = f"""
SELECT DISTINCT old_id, new_id, base_scene_code, merchant_id
FROM tmp_rule_id_mapping
WHERE table_name = '{parent_table}'
AND old_id != new_id
AND merchant_id = {merchant_id}
ORDER BY merchant_id, old_id, new_id;
"""
mappings = self.db.execute_query(query_mapping_sql)
self.logger.info(f" 找到 {len(mappings)} 条表6的映射关系需要处理")
# 收集所有需要插入的数据
insert_batch = []
for mapping in mappings:
old_division_id = mapping[0]
new_division_id = mapping[1]
base_scene_code = mapping[2]
merchant_id = mapping[3]
# 查询原division_rule_id对应的所有表7记录
query_sql = f"""
SELECT id, division_rule_id, group_type, goods_type_group_id, test_flag,
goods_cost_convert_rate, virtual_account_cost_convert_rate,
recovery_cost_convert_rate, dj_cost_convert_rate, third_party_cost_convert_rate
FROM {table_name}
WHERE division_rule_id = {old_division_id};
"""
# 得到原来一个分账规则对应的多个分账分组(全部品类和特殊品类)
records = self.db.execute_query(query_sql)
for record in records:
old_id = record[0]
group_type = record[2]
goods_type_group_id = record[3] if record[3] is not None else 'NULL'
test_flag = f"'{record[4]}'" if record[4] is not None else 'NULL'
goods_cost_convert_rate = record[5]
virtual_account_cost_convert_rate = record[6]
recovery_cost_convert_rate = record[7]
dj_cost_convert_rate = record[8]
third_party_cost_convert_rate = record[9]
insert_batch.append({
'old_id': old_id,
'new_division_id': new_division_id,
'group_type': group_type,
'goods_type_group_id': goods_type_group_id,
'test_flag': test_flag,
'goods_cost_convert_rate': goods_cost_convert_rate,
'virtual_account_cost_convert_rate': virtual_account_cost_convert_rate,
'recovery_cost_convert_rate': recovery_cost_convert_rate,
'dj_cost_convert_rate': dj_cost_convert_rate,
'third_party_cost_convert_rate': third_party_cost_convert_rate,
'base_scene_code': base_scene_code,
'merchant_id': merchant_id
})
total_count = len(insert_batch)
self.logger.info(f" 收集到 {total_count} 条需要插入的记录")
if total_count == 0:
self.logger.info(f"第4步完成,共复制 0 条记录")
return
# 批量插入
batch_size = 10000
total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量插入,共 {total_batches} 个批次,每批 {batch_size} 条")
copy_count = 0
for batch_idx in range(total_batches):
start_idx = batch_idx * batch_size
end_idx = min(start_idx + batch_size, total_count)
batch = insert_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建批量插入SQL
values = []
for item in batch:
values.append(
f"({item['new_division_id']}, {item['group_type']}, {item['goods_type_group_id']}, {item['test_flag']}, "
f"{item['goods_cost_convert_rate']}, {item['virtual_account_cost_convert_rate']}, "
f"{item['recovery_cost_convert_rate']}, {item['dj_cost_convert_rate']}, {item['third_party_cost_convert_rate']}, "
f"'{DATA_MIGRATION_USER}', NOW(), '{DATA_MIGRATION_USER}', NOW(), 'N')"
)
insert_sql = f"""
INSERT INTO {table_name}
(division_rule_id, group_type, goods_type_group_id, test_flag,
goods_cost_convert_rate, virtual_account_cost_convert_rate,
recovery_cost_convert_rate, dj_cost_convert_rate, third_party_cost_convert_rate,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES {','.join(values)};
"""
if self.db.execute_update(insert_sql):
# 获取第一个插入记录的ID
first_new_id = self.db.execute_query_one("SELECT LAST_INSERT_ID();")[0]
# 为批次中的每条记录建立映射关系
for i, item in enumerate(batch):
new_id = first_new_id + i
self.id_mapper.add_mapping(table_name, item['old_id'], new_id, item['base_scene_code'], item['merchant_id'])
copy_count += 1
self.logger.info(f" 批次 {batch_num}/{total_batches} 插入完成,本批 {len(batch)} 条,累计 {copy_count} 条")
self.logger.info(f"第4步完成,共复制 {copy_count} 条记录")
def step5_process_goods_type_group(self, merchant_id=None):
"""
第5步:处理商品分组表(表4)
dj_car_life_goods_type_group
通过表2反推需要拆分的表4记录
Args:
merchant_id: 商户ID,必须提供
"""
if merchant_id is None:
raise ValueError("step5_process_goods_type_group 必须提供 merchant_id 参数")
self.logger.info("=" * 80)
self.logger.info(f"第5步:开始处理商品分组表(商户ID: {merchant_id})")
table_name = 'dj_car_life_goods_type_group'
settle_rule_table = 'dj_car_life_merchant_goods_type_group_settle_rule'
# 通过表2的映射关系,找到需要拆分的表4记录
query_sql = f"""
SELECT DISTINCT
gtg.id as old_goods_type_group_id,
gtg.use_type,
gtg.goods_source,
m.new_id as new_settle_rule_group_id,
m.base_scene_code,
m.merchant_id
FROM dj_car_life_goods_type_group gtg
JOIN dj_car_life_merchant_goods_type_group_settle_rule gtgsr_old
ON gtgsr_old.goods_type_group_id = gtg.id
JOIN tmp_rule_id_mapping m
ON m.table_name = '{settle_rule_table}'
AND m.old_id = gtgsr_old.id
AND m.old_id != m.new_id
AND m.merchant_id = {merchant_id}
ORDER BY m.merchant_id, gtg.id, m.base_scene_code;
"""
records = self.db.execute_query(query_sql)
self.logger.info(f" 找到 {len(records)} 条需要复制的表4记录")
# 去重并收集所有需要插入的数据
processed_pairs = set()
insert_batch = []
for record in records:
old_id = record[0]
use_type = record[1]
goods_source = record[2]
new_settle_rule_group_id = record[3]
base_scene_code = record[4]
merchant_id = record[5]
# 去重检查
pair_key = (old_id, base_scene_code)
if pair_key in processed_pairs:
continue
processed_pairs.add(pair_key)
insert_batch.append({
'old_id': old_id,
'use_type': use_type,
'goods_source': goods_source,
'new_settle_rule_group_id': new_settle_rule_group_id,
'base_scene_code': base_scene_code,
'merchant_id': merchant_id
})
total_count = len(insert_batch)
self.logger.info(f" 去重后需要插入 {total_count} 条记录")
# 批量插入表4
batch_size = 10000
total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量插入表4,共 {total_batches} 个批次,每批 {batch_size} 条")
copy_count = 0
for batch_idx in range(total_batches):
start_idx = batch_idx * batch_size
end_idx = min(start_idx + batch_size, total_count)
batch = insert_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建批量插入SQL
values = []
for item in batch:
values.append(f"({item['use_type']}, {item['goods_source']}, "
f"'{DATA_MIGRATION_USER}', NOW(), '{DATA_MIGRATION_USER}', NOW(), 'N')")
insert_sql = f"""
INSERT INTO {table_name}
(use_type, goods_source, created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES {','.join(values)};
"""
if self.db.execute_update(insert_sql):
# 获取批量插入的起始ID
first_id_sql = "SELECT LAST_INSERT_ID();"
result = self.db.execute_query_one(first_id_sql)
if result:
first_new_id = result[0]
# 为每条记录建立映射关系
for i, item in enumerate(batch):
new_id = first_new_id + i
self.id_mapper.add_mapping(table_name, item['old_id'], new_id, item['base_scene_code'], item['merchant_id'])
copy_count += 1
self.logger.info(f" 批次 {batch_num}/{total_batches} 插入完成,本批 {len(batch)} 条,累计 {copy_count} 条")
self.logger.info(f" 表4插入完成,共插入 {copy_count} 条记录")
# 批量更新表2中的 goods_type_group_id
self._batch_update_settle_rule_goods_type_group_id(insert_batch)
# 更新表7(分账规则分组表)中的 goods_type_group_id
self._update_division_rule_group_goods_type_group_id()
self.logger.info(f"第5步完成,共复制 {copy_count} 条记录")
def _batch_update_settle_rule_goods_type_group_id(self, insert_batch):
"""
批量更新表2(dj_car_life_merchant_goods_type_group_settle_rule)中的 goods_type_group_id
使用临时表关联更新,优化大数据量场景性能
"""
self.logger.info(" 开始批量更新表2中的 goods_type_group_id...")
settle_rule_table = 'dj_car_life_merchant_goods_type_group_settle_rule'
goods_type_group_table = 'dj_car_life_goods_type_group'
temp_table = 'tmp_settle_rule_update_batch'
total_count = len(insert_batch)
self.logger.info(f" 待更新数据量: {total_count} 条")
try:
# 1. 创建临时表
create_temp_sql = f"""
CREATE TABLE {temp_table} (
old_id BIGINT NOT NULL COMMENT '原goods_type_group的ID',
base_scene_code VARCHAR(20) NOT NULL COMMENT '场景编码',
new_settle_rule_group_id BIGINT NOT NULL COMMENT '新的settle_rule记录ID',
INDEX idx_old_scene (old_id, base_scene_code),
INDEX idx_settle_rule (new_settle_rule_group_id)
) ENGINE=MEMORY DEFAULT CHARSET=utf8mb4 COMMENT='临时表:用于批量更新settle_rule的goods_type_group_id';
"""
self.db.execute_update(create_temp_sql)
self.logger.info(f" 临时表 {temp_table} 创建成功")
# 2. 分批插入临时表(每批1万条,避免SQL过长)
insert_batch_size = 20000
total_batches = (total_count + insert_batch_size - 1) // insert_batch_size
self.logger.info(f" 开始插入临时表,共 {total_batches} 个批次")
for batch_idx in range(total_batches):
start_idx = batch_idx * insert_batch_size
end_idx = min(start_idx + insert_batch_size, total_count)
batch = insert_batch[start_idx:end_idx]
# 构建批量插入SQL
values = []
for item in batch:
old_id = item['old_id']
base_scene_code = item['base_scene_code']
new_settle_rule_group_id = item['new_settle_rule_group_id']
values.append(f"({old_id}, '{base_scene_code}', {new_settle_rule_group_id})")
insert_sql = f"""
INSERT INTO {temp_table} (old_id, base_scene_code, new_settle_rule_group_id)
VALUES {','.join(values)};
"""
self.db.execute_update(insert_sql)
self.logger.info(f" 临时表插入进度: {batch_idx + 1}/{total_batches},本批 {len(batch)} 条")
# 3. 一次性关联更新(核心优化:避免大量OR条件和CASE WHEN)
update_sql = f"""
UPDATE {settle_rule_table} sr
INNER JOIN {temp_table} tmp ON sr.id = tmp.new_settle_rule_group_id
INNER JOIN tmp_rule_id_mapping map ON
map.table_name = '{goods_type_group_table}'
AND map.old_id = tmp.old_id
AND map.base_scene_code = tmp.base_scene_code
SET sr.goods_type_group_id = map.new_id;
"""
self.logger.info(" 开始执行关联更新...")
if self.db.execute_update(update_sql):
self.logger.info(f" 表2更新完成,共更新 {total_count} 条记录")
else:
self.logger.error(" 表2更新失败")
except Exception as e:
self.logger.error(f" 批量更新表2失败: {e}")
raise
finally:
# 4. 清理临时表
try:
drop_sql = f"DROP TEMPORARY TABLE IF EXISTS {temp_table};"
self.db.execute_update(drop_sql)
self.logger.info(f" 临时表 {temp_table} 已清理")
except Exception as e:
self.logger.warning(f" 清理临时表失败: {e}")
def _update_division_rule_group_goods_type_group_id(self):
"""
更新表7(dj_car_life_merchant_goods_type_group_division_rule)中的 goods_type_group_id
根据表4的映射关系更新 - 优化版本:一次性关联查询
"""
self.logger.info(" 开始批量更新表7中的 goods_type_group_id...")
division_rule_group_table = 'dj_car_life_merchant_goods_type_group_division_rule'
goods_type_group_table = 'dj_car_life_goods_type_group'
# 一次性关联查询所有需要更新的记录(优化:14万次查询 → 1次查询)
query_sql = f"""
SELECT
gtgdr.id,
m_goods.new_id as new_goods_type_group_id
FROM {division_rule_group_table} gtgdr
JOIN tmp_rule_id_mapping m_division
ON m_division.table_name = 'dj_car_life_merchant_division_rule'
AND m_division.new_id = gtgdr.division_rule_id
JOIN tmp_rule_id_mapping m_goods
ON m_goods.table_name = '{goods_type_group_table}'
AND m_goods.old_id = gtgdr.goods_type_group_id
AND m_goods.base_scene_code = m_division.base_scene_code
AND m_goods.old_id != m_goods.new_id;
"""
self.logger.info(" 执行关联查询获取需要更新的记录...")
records = self.db.execute_query(query_sql)
self.logger.info(f" 查询到 {len(records)} 条需要更新的记录")
# 收集所有需要更新的记录
update_batch = []
for record in records:
record_id = record[0]
new_goods_type_group_id = record[1]
update_batch.append({
'id': record_id,
'new_goods_type_group_id': new_goods_type_group_id
})
# 批量更新
batch_size = 10000
total_count = len(update_batch)
total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量更新表7,共 {total_batches} 个批次,每批 {batch_size} 条")
update_count = 0
for batch_idx in range(total_batches):
start_idx = batch_idx * batch_size
end_idx = min(start_idx + batch_size, total_count)
batch = update_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建 CASE WHEN 批量更新SQL
case_when = []
ids = []
for item in batch:
case_when.append(f"WHEN id = {item['id']} THEN {item['new_goods_type_group_id']}")
ids.append(str(item['id']))
update_sql = f"""
UPDATE {division_rule_group_table}
SET goods_type_group_id = CASE
{' '.join(case_when)}
END
WHERE id IN ({','.join(ids)});
"""
if self.db.execute_update(update_sql):
update_count += len(batch)
self.logger.info(f" 批次 {batch_num}/{total_batches} 更新完成,本批 {len(batch)} 条,累计 {update_count} 条")
self.logger.info(f" 表7的 goods_type_group_id 更新完成,共更新 {update_count} 条记录")
def step6_process_expense_category_rule_finance(self, merchant_id=None):
"""
第6步:处理费用类目规则表(表3)- 财务规则侧
dj_car_life_merchant_expense_category_rule (rule_type=1)
Args:
merchant_id: 商户ID,必须提供
"""
if merchant_id is None:
raise ValueError("step6_process_expense_category_rule_finance 必须提供 merchant_id 参数")
self.logger.info("=" * 80)
self.logger.info(f"第6步:开始处理费用类目规则表(财务侧)- 商户 {merchant_id}")
table_name = 'dj_car_life_merchant_expense_category_rule'
parent_table = 'dj_car_life_merchant_goods_type_group_settle_rule'
# 查询表2的所有映射关系 140754
query_mapping_sql = f"""
SELECT DISTINCT old_id, new_id, base_scene_code, merchant_id
FROM tmp_rule_id_mapping
WHERE table_name = '{parent_table}'
AND old_id != new_id
AND merchant_id = {merchant_id}
ORDER BY merchant_id, old_id, new_id;
"""
mappings = self.db.execute_query(query_mapping_sql)
self.logger.info(f" 找到 {len(mappings)} 条表2的映射关系需要处理")
# 收集所有需要插入的数据
insert_batch = []
for mapping in mappings:
old_goods_type_group_rule_id = mapping[0]
new_goods_type_group_rule_id = mapping[1]
base_scene_code = mapping[2]
merchant_id = mapping[3]
# 查询原goods_type_group_rule_id对应的所有表3记录(rule_type=1)
query_sql = f"""
SELECT id, rule_type, goods_type_group_rule_id, expense_category_id, expense_category_name,
parent_expense_category_id, parent_expense_category_name, target_type, node_type,
parent_id, category_to_sort, calculate_mode, expense_category_calculate_type,
expense_category_value, target_merchant_id, target_merchant_name, deleted_flag
FROM {table_name}
WHERE rule_type = 1
AND goods_type_group_rule_id = {old_goods_type_group_rule_id};
"""
records = self.db.execute_query(query_sql)
for record in records:
old_id = record[0]
rule_type = record[1]
expense_category_id = record[3]
expense_category_name = record[4]
parent_expense_category_id = record[5] if record[5] is not None else 'NULL'
parent_expense_category_name = f"'{record[6]}'" if record[6] is not None else 'NULL'
target_type = record[7]
node_type = record[8] if record[8] is not None else 'NULL'
parent_id = record[9] if record[9] is not None else 'NULL'
category_to_sort = record[10] if record[10] is not None else 'NULL'
calculate_mode = record[11] if record[11] is not None else 'NULL'
expense_category_calculate_type = record[12] if record[12] is not None else 'NULL'
expense_category_value = record[13] if record[13] is not None else 'NULL'
target_merchant_id = record[14] if record[14] is not None else 'NULL'
target_merchant_name = f"'{record[15]}'" if record[15] is not None else 'NULL'
deleted_flag = record[16] if record[16] is not None else 'N'
insert_batch.append({
'old_id': old_id,
'rule_type': rule_type,
'new_goods_type_group_rule_id': new_goods_type_group_rule_id,
'expense_category_id': expense_category_id,
'expense_category_name': expense_category_name,
'parent_expense_category_id': parent_expense_category_id,
'parent_expense_category_name': parent_expense_category_name,
'target_type': target_type,
'node_type': node_type,
'parent_id': parent_id,
'category_to_sort': category_to_sort,
'calculate_mode': calculate_mode,
'expense_category_calculate_type': expense_category_calculate_type,
'expense_category_value': expense_category_value,
'target_merchant_id': target_merchant_id,
'target_merchant_name': target_merchant_name,
'deleted_flag': deleted_flag,
'base_scene_code': base_scene_code,
'merchant_id': merchant_id
})
total_count = len(insert_batch)
self.logger.info(f" 收集到 {total_count} 条需要插入的记录")
# 批量插入
batch_size = 100000
total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量插入,共 {total_batches} 个批次,每批 {batch_size} 条")
copy_count = 0
for batch_idx in range(total_batches):
start_idx = batch_idx * batch_size
end_idx = min(start_idx + batch_size, total_count)
batch = insert_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建批量插入SQL
values = []
for item in batch:
values.append(
f"({item['rule_type']}, {item['new_goods_type_group_rule_id']}, "
f"{item['expense_category_id']}, '{item['expense_category_name']}', "
f"{item['parent_expense_category_id']}, {item['parent_expense_category_name']}, "
f"{item['target_type']}, {item['node_type']}, {item['parent_id']}, "
f"{item['category_to_sort']}, {item['calculate_mode']}, "
f"{item['expense_category_calculate_type']}, {item['expense_category_value']}, "
f"{item['target_merchant_id']}, {item['target_merchant_name']}, "
f"'{DATA_MIGRATION_USER}', NOW(), '{DATA_MIGRATION_USER}', NOW(), '{item['deleted_flag']}')"
)
insert_sql = f"""
INSERT INTO {table_name}
(rule_type, goods_type_group_rule_id, expense_category_id, expense_category_name,
parent_expense_category_id, parent_expense_category_name, target_type, node_type,
parent_id, category_to_sort, calculate_mode, expense_category_calculate_type,
expense_category_value, target_merchant_id, target_merchant_name,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES {','.join(values)};
"""
if self.db.execute_update(insert_sql):
# 获取批量插入的起始ID
first_id_sql = "SELECT LAST_INSERT_ID();"
result = self.db.execute_query_one(first_id_sql)
if result:
first_new_id = result[0]
# 为每条记录建立映射关系
for i, item in enumerate(batch):
new_id = first_new_id + i
self.id_mapper.add_mapping(table_name, item['old_id'], new_id, item['base_scene_code'], item['merchant_id'])
copy_count += 1
self.logger.info(f" 批次 {batch_num}/{total_batches} 插入完成,本批 {len(batch)} 条,累计 {copy_count} 条")
self.logger.info(f"第6步完成,共复制 {copy_count} 条记录")
def step7_process_goods_type_group_relation_finance(self, merchant_id=None):
"""
第7步:处理商品分组关系表(表5)- 财务规则侧
Args:
merchant_id: 商户ID,必须提供
dj_car_life_goods_type_group_relation (rule_type=1)
"""
if merchant_id is None:
raise ValueError("step7_process_goods_type_group_relation_finance 必须提供 merchant_id 参数")
self.logger.info("=" * 80)
self.logger.info(f"第7步:开始处理商品分组关系表(财务侧)- 商户 {merchant_id}")
table_name = 'dj_car_life_goods_type_group_relation'
parent_table = 'dj_car_life_goods_type_group'
# 查询表4的所有映射关系
query_mapping_sql = f"""
SELECT DISTINCT old_id, new_id, base_scene_code, merchant_id
FROM tmp_rule_id_mapping
WHERE table_name = '{parent_table}'
AND old_id != new_id
AND merchant_id = {merchant_id}
ORDER BY merchant_id, old_id, new_id;
"""
mappings = self.db.execute_query(query_mapping_sql)
self.logger.info(f" 找到 {len(mappings)} 条表4的映射关系需要处理")
# 收集所有需要插入的数据
insert_batch = []
for mapping in mappings:
old_goods_type_group_id = mapping[0]
new_goods_type_group_id = mapping[1]
base_scene_code = mapping[2]
merchant_id = mapping[3]
# 查询原goods_type_group_rule_id对应的所有表5记录(rule_type=1)
query_sql = f"""
SELECT id, rule_type, goods_type_group_rule_id, category_type,
upgrade_goods_id, merchant_goods_code, goods_type, goods_type_name,
package_code, package_name
FROM {table_name}
WHERE rule_type = 1
AND goods_type_group_rule_id = {old_goods_type_group_id};
"""
records = self.db.execute_query(query_sql)
for record in records:
old_id = record[0]
rule_type = record[1]
category_type = record[3]
upgrade_goods_id = record[4]
merchant_goods_code = record[5]
goods_type = record[6]
goods_type_name = record[7]
package_code = record[8]
package_name = record[9]
insert_batch.append({
'old_id': old_id,
'rule_type': rule_type,
'new_goods_type_group_id': new_goods_type_group_id,
'category_type': category_type,
'upgrade_goods_id': upgrade_goods_id,
'merchant_goods_code': merchant_goods_code,
'goods_type': goods_type,
'goods_type_name': goods_type_name,
'package_code': package_code,
'package_name': package_name,
'base_scene_code': base_scene_code,
'merchant_id': merchant_id
})
total_count = len(insert_batch)
self.logger.info(f" 收集到 {total_count} 条需要插入的记录")
# 批量插入
batch_size = 100000
total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量插入,共 {total_batches} 个批次,每批 {batch_size} 条")
copy_count = 0
for batch_idx in range(total_batches):
start_idx = batch_idx * batch_size
end_idx = min(start_idx + batch_size, total_count)
batch = insert_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建参数化查询的值列表
values_list = []
for item in batch:
values_list.append((
item['rule_type'],
item['new_goods_type_group_id'],
item['category_type'],
item['upgrade_goods_id'],
item['merchant_goods_code'],
item['goods_type'],
item['goods_type_name'],
item['package_code'],
item['package_name'],
DATA_MIGRATION_USER,
DATA_MIGRATION_USER
))
insert_sql = f"""
INSERT INTO {table_name}
(rule_type, goods_type_group_rule_id, category_type,
upgrade_goods_id, merchant_goods_code, goods_type, goods_type_name,
package_code, package_name,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), %s, NOW(), 'N')
"""
if self.db.execute_batch_insert(insert_sql, values_list):
# 获取批量插入的起始ID
first_id_sql = "SELECT LAST_INSERT_ID();"
result = self.db.execute_query_one(first_id_sql)
if result:
first_new_id = result[0]
# 为每条记录建立映射关系
for i, item in enumerate(batch):
new_id = first_new_id + i
self.id_mapper.add_mapping(table_name, item['old_id'], new_id, item['base_scene_code'], item['merchant_id'])
copy_count += 1
self.logger.info(f" 批次 {batch_num}/{total_batches} 插入完成,本批 {len(batch)} 条,累计 {copy_count} 条")
self.logger.info(f"第7步完成,共复制 {copy_count} 条记录")
def step8_process_distribution_rule(self, merchant_id=None):
"""
第8步:处理分账明细规则表(表8)
dj_car_life_merchant_distribution_rule
Args:
merchant_id: 商户ID,必须提供
"""
if merchant_id is None:
raise ValueError("step8_process_distribution_rule 必须提供 merchant_id 参数")
self.logger.info("=" * 80)
self.logger.info(f"第8步:开始处理分账明细规则表 - 商户 {merchant_id}")
table_name = 'dj_car_life_merchant_distribution_rule'
parent_table = 'dj_car_life_merchant_goods_type_group_division_rule'
# 查询表7的所有映射关系
query_mapping_sql = f"""
SELECT DISTINCT old_id, new_id, base_scene_code, merchant_id
FROM tmp_rule_id_mapping
WHERE table_name = '{parent_table}'
AND old_id != new_id
AND merchant_id = {merchant_id}
ORDER BY merchant_id, old_id, new_id;
"""
mappings = self.db.execute_query(query_mapping_sql)
self.logger.info(f" 找到 {len(mappings)} 条表7的映射关系需要处理")
# 收集所有需要插入的数据
insert_batch = []
for mapping in mappings:
old_goods_type_group_rule_id = mapping[0]
new_goods_type_group_rule_id = mapping[1]
base_scene_code = mapping[2]
merchant_id = mapping[3]
# 查询原goods_type_group_rule_id对应的所有表8记录
query_sql = f"""
SELECT id, goods_type_group_rule_id, rule_type, target_merchant_type,
target_merchant_level, merchant_id, merchant_name,
expense_category_id, expense_category_name
FROM {table_name}
WHERE goods_type_group_rule_id = {old_goods_type_group_rule_id};
"""
records = self.db.execute_query(query_sql)
for record in records:
old_id = record[0]
rule_type = record[2]
target_merchant_type = record[3] if record[3] is not None else 'NULL'
target_merchant_level = record[4] if record[4] is not None else 1
merchant_id = record[5] if record[5] is not None else 'NULL'
merchant_name = f"'{record[6]}'" if record[6] is not None else 'NULL'
expense_category_id = record[7] if record[7] is not None else 'NULL'
expense_category_name = f"'{record[8]}'" if record[8] is not None else 'NULL'
insert_batch.append({
'old_id': old_id,
'new_goods_type_group_rule_id': new_goods_type_group_rule_id,
'rule_type': rule_type,
'target_merchant_type': target_merchant_type,
'target_merchant_level': target_merchant_level,
'merchant_id': merchant_id,
'merchant_name': merchant_name,
'expense_category_id': expense_category_id,
'expense_category_name': expense_category_name,
'base_scene_code': base_scene_code,
'parent_merchant_id': mapping[3]
})
total_count = len(insert_batch)
self.logger.info(f" 收集到 {total_count} 条需要插入的记录")
# 批量插入
batch_size = 200000
total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量插入,共 {total_batches} 个批次,每批 {batch_size} 条")
copy_count = 0
for batch_idx in range(total_batches):
start_idx = batch_idx * batch_size
end_idx = min(start_idx + batch_size, total_count)
batch = insert_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建批量插入SQL
values = []
for item in batch:
values.append(
f"({item['new_goods_type_group_rule_id']}, {item['rule_type']}, "
f"{item['target_merchant_type']}, {item['target_merchant_level']}, "
f"{item['merchant_id']}, {item['merchant_name']}, "
f"{item['expense_category_id']}, {item['expense_category_name']}, "
f"'{DATA_MIGRATION_USER}', NOW(), '{DATA_MIGRATION_USER}', NOW(), 'N')"
)
insert_sql = f"""
INSERT INTO {table_name}
(goods_type_group_rule_id, rule_type, target_merchant_type,
target_merchant_level, merchant_id, merchant_name,
expense_category_id, expense_category_name,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES {','.join(values)};
"""
if self.db.execute_update(insert_sql):
# 获取批量插入的起始ID
first_id_sql = "SELECT LAST_INSERT_ID();"
result = self.db.execute_query_one(first_id_sql)
if result:
first_new_id = result[0]
# 为每条记录建立映射关系
for i, item in enumerate(batch):
new_id = first_new_id + i
self.id_mapper.add_mapping(table_name, item['old_id'], new_id, item['base_scene_code'], item['parent_merchant_id'])
copy_count += 1
self.logger.info(f" 批次 {batch_num}/{total_batches} 插入完成,本批 {len(batch)} 条,累计 {copy_count} 条")
self.logger.info(f"第8步完成,共复制 {copy_count} 条记录")
def step9_process_division_rule_auto(self, merchant_id=None):
"""
第9步:处理自动分账配置表(表13)
dj_car_life_division_rule_auto
Args:
merchant_id: 商户ID,必须提供
"""
if merchant_id is None:
raise ValueError("step9_process_division_rule_auto 必须提供 merchant_id 参数")
self.logger.info("=" * 80)
self.logger.info(f"第9步:开始处理自动分账配置表 - 商户 {merchant_id}")
table_name = 'dj_car_life_division_rule_auto'
parent_table = 'dj_car_life_merchant_division_rule'
# 查询表6的所有映射关系
query_mapping_sql = f"""
SELECT DISTINCT old_id, new_id, base_scene_code, merchant_id
FROM tmp_rule_id_mapping
WHERE table_name = '{parent_table}'
AND old_id != new_id
AND merchant_id = {merchant_id}
ORDER BY merchant_id, old_id, new_id;
"""
mappings = self.db.execute_query(query_mapping_sql)
self.logger.info(f" 找到 {len(mappings)} 条表6的映射关系需要处理")
# 收集所有需要插入的数据
insert_batch = []
for mapping in mappings:
old_division_rule_id = mapping[0]
new_division_rule_id = mapping[1]
base_scene_code = mapping[2]
merchant_id = mapping[3]
# 查询原division_rule_id对应的所有表13记录
query_sql = f"""
SELECT id, division_rule_id, payment_channel_id, payment_channel_name,
division_type, auto_flag, test_flag, settle_time_type, settle_time
FROM {table_name}
WHERE division_rule_id = {old_division_rule_id};
"""
records = self.db.execute_query(query_sql)
for record in records:
old_id = record[0]
payment_channel_id = f"'{record[2]}'" if record[2] is not None else 'NULL'
payment_channel_name = f"'{record[3]}'" if record[3] is not None else 'NULL'
division_type = record[4] if record[4] is not None else 1
auto_flag = record[5]
test_flag = f"'{record[6]}'" if record[6] is not None else 'NULL'
settle_time_type = record[7] if record[7] is not None else 'NULL'
settle_time = record[8] if record[8] is not None else 'NULL'
insert_batch.append({
'old_id': old_id,
'new_division_rule_id': new_division_rule_id,
'payment_channel_id': payment_channel_id,
'payment_channel_name': payment_channel_name,
'division_type': division_type,
'auto_flag': auto_flag,
'test_flag': test_flag,
'settle_time_type': settle_time_type,
'settle_time': settle_time,
'base_scene_code': base_scene_code,
'merchant_id': merchant_id
})
total_count = len(insert_batch)
self.logger.info(f" 收集到 {total_count} 条需要插入的记录")
if total_count == 0:
self.logger.info(f"第9步完成,共复制 0 条记录")
return
# 批量插入
batch_size = 10000
total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量插入,共 {total_batches} 个批次,每批 {batch_size} 条")
copy_count = 0
for batch_idx in range(total_batches):
start_idx = batch_idx * batch_size
end_idx = min(start_idx + batch_size, total_count)
batch = insert_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建批量插入SQL
values = []
for item in batch:
values.append(
f"({item['new_division_rule_id']}, {item['payment_channel_id']}, {item['payment_channel_name']}, "
f"{item['division_type']}, '{item['auto_flag']}', {item['test_flag']}, "
f"{item['settle_time_type']}, {item['settle_time']}, "
f"'{DATA_MIGRATION_USER}', NOW(), '{DATA_MIGRATION_USER}', NOW(), 'N')"
)
insert_sql = f"""
INSERT INTO {table_name}
(division_rule_id, payment_channel_id, payment_channel_name,
division_type, auto_flag, test_flag, settle_time_type, settle_time,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES {','.join(values)};
"""
if self.db.execute_update(insert_sql):
# 获取第一个插入记录的ID
first_new_id = self.db.execute_query_one("SELECT LAST_INSERT_ID();")[0]
# 为批次中的每条记录建立映射关系
for i, item in enumerate(batch):
new_id = first_new_id + i
self.id_mapper.add_mapping(table_name, item['old_id'], new_id, item['base_scene_code'], item['merchant_id'])
copy_count += 1
self.logger.info(f" 批次 {batch_num}/{total_batches} 插入完成,本批 {len(batch)} 条,累计 {copy_count} 条")
self.logger.info(f"第9步完成,共复制 {copy_count} 条记录")
def step10_process_reconciliation_rule(self):
"""
第10步:处理对账规则主表(表9)
dj_car_life_merchant_reconciliation_rule
"""
self.logger.info("=" * 80)
self.logger.info("第10步:开始处理对账规则主表")
table_name = 'dj_car_life_merchant_reconciliation_rule'
# 1. 处理 scene_type != 0 的记录
self.logger.info("处理 scene_type != 0 的记录...")
for scene_type, base_scene_code in SCENE_TYPE_MAPPING.items():
if self.test_mode:
# 测试模式:每个 scene_type 只更新一条
update_sql = f"""
UPDATE {table_name}
SET base_scene_code = '{base_scene_code}',
updated_by = '{DATA_MIGRATION_USER}',
updated_date = NOW()
WHERE id = (
SELECT id FROM (
SELECT id FROM {table_name}
WHERE scene_type = {scene_type}
AND (base_scene_code IS NULL OR base_scene_code = '')
ORDER BY id DESC
LIMIT 1
) tmp
);
"""
self.logger.info(f" [测试模式] scene_type={scene_type} 只更新最新一条为 base_scene_code={base_scene_code}")
else:
# 正常模式:更新所有记录
update_sql = f"""
UPDATE {table_name}
SET base_scene_code = '{base_scene_code}',
updated_by = '{DATA_MIGRATION_USER}',
updated_date = NOW()
WHERE scene_type = {scene_type} and merchant_id = 44210895
AND (base_scene_code IS NULL OR base_scene_code = '');
"""
if self.db.execute_update(update_sql):
self.logger.info(f" scene_type={scene_type} 更新为 base_scene_code={base_scene_code}")
# 2. 处理 scene_type = 0 的记录
self.logger.info("处理 scene_type = 0 的记录...")
# 2.1 查询所有需要拆分的记录
if self.test_mode:
# 测试模式:只取ID最大的一条
query_sql = f"""
SELECT id, source, merchant_id, scene_type,
shop_merchant_total_fee_calculate_type, shop_merchant_expense_category_value,
partner_merchant_total_fee_calculate_type, partner_merchant_expense_category_value,
enable_flag, submit_flag, created_by, created_date, updated_by, updated_date
FROM {table_name}
WHERE scene_type = 0
AND (base_scene_code IS NULL OR base_scene_code = '')
ORDER BY id DESC
LIMIT 1;
"""
self.logger.info(" [测试模式] 只处理 scene_type=0 的最新一条记录")
else:
# 正常模式:查询所有记录
query_sql = f"""
SELECT id, source, merchant_id, scene_type,
shop_merchant_total_fee_calculate_type, shop_merchant_expense_category_value,
partner_merchant_total_fee_calculate_type, partner_merchant_expense_category_value,
enable_flag, submit_flag, created_by, created_date, updated_by, updated_date, deleted_flag
FROM {table_name}
WHERE scene_type = 0 and merchant_id = 44210895
AND (base_scene_code IS NULL OR base_scene_code = '');
"""
records = self.db.execute_query(query_sql)
self.logger.info(f" 找到 {len(records)} 条需要拆分的记录")
# 2.2 更新原记录
first_code = SCENE_TYPE_0_SPLIT[0]
if self.test_mode and len(records) > 0:
# 测试模式:只更新查询出来的那一条记录
record_id = records[0][0]
update_sql = f"""
UPDATE {table_name}
SET base_scene_code = '{first_code}',
updated_by = '{DATA_MIGRATION_USER}',
updated_date = NOW()
WHERE id = {record_id};
"""
else:
# 正常模式:更新所有记录
update_sql = f"""
UPDATE {table_name}
SET base_scene_code = '{first_code}',
updated_by = '{DATA_MIGRATION_USER}',
updated_date = NOW()
WHERE scene_type = 0 and merchant_id = 44210895
AND (base_scene_code IS NULL OR base_scene_code = '');
"""
if self.db.execute_update(update_sql):
self.logger.info(f" 原记录已更新为 base_scene_code={first_code}")
# 2.3 复制插入新记录(批量操作)
copy_codes = SCENE_TYPE_0_SPLIT[1:]
insert_batch = []
for record in records:
old_id = record[0]
source = record[1] if record[1] is not None else 'NULL'
merchant_id = record[2]
scene_type = record[3]
shop_merchant_total_fee_calculate_type = record[4] if record[4] is not None else 'NULL'
shop_merchant_expense_category_value = record[5] if record[5] is not None else 'NULL'
partner_merchant_total_fee_calculate_type = record[6] if record[6] is not None else 'NULL'
partner_merchant_expense_category_value = record[7] if record[7] is not None else 'NULL'
enable_flag = f"'{record[8]}'" if record[8] is not None else 'NULL'
submit_flag = f"'{record[9]}'" if record[9] is not None else 'NULL'
created_date = record[11] # 保存原记录的 created_date
deleted_flag = f"'{record[14]}'" if record[14] is not None else "'N'"
# 处理 created_date 格式
if created_date is None:
self.logger.warning(f" 记录 id={old_id} 的 created_date 为 NULL,跳过复制")
continue
elif isinstance(created_date, str):
created_date_str = created_date
else:
# datetime 对象转字符串
created_date_str = created_date.strftime('%Y-%m-%d %H:%M:%S')
for new_code in copy_codes:
insert_batch.append({
'old_id': old_id,
'source': source,
'merchant_id': merchant_id,
'scene_type': scene_type,
'shop_merchant_total_fee_calculate_type': shop_merchant_total_fee_calculate_type,
'shop_merchant_expense_category_value': shop_merchant_expense_category_value,
'partner_merchant_total_fee_calculate_type': partner_merchant_total_fee_calculate_type,
'partner_merchant_expense_category_value': partner_merchant_expense_category_value,
'enable_flag': enable_flag,
'submit_flag': submit_flag,
'created_date_str': created_date_str,
'base_scene_code': new_code,
'deleted_flag': deleted_flag
})
total_count = len(insert_batch)
self.logger.info(f" 收集到 {total_count} 条需要插入的记录")
if total_count > 0:
# 批量插入
batch_size = 10000
total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量插入,共 {total_batches} 个批次,每批 {batch_size} 条")
copy_count = 0
for batch_idx in range(total_batches):
start_idx = batch_idx * batch_size
end_idx = min(start_idx + batch_size, total_count)
batch = insert_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建批量插入SQL
values = []
for item in batch:
values.append(
f"({item['source']}, {item['merchant_id']}, {item['scene_type']}, '{item['base_scene_code']}', "
f"{item['shop_merchant_total_fee_calculate_type']}, {item['shop_merchant_expense_category_value']}, "
f"{item['partner_merchant_total_fee_calculate_type']}, {item['partner_merchant_expense_category_value']}, "
f"{item['enable_flag']}, {item['submit_flag']}, "
f"'{DATA_MIGRATION_USER}', '{item['created_date_str']}', '{DATA_MIGRATION_USER}', NOW(), {item['deleted_flag']})"
)
insert_sql = f"""
INSERT INTO {table_name}
(source, merchant_id, scene_type, base_scene_code,
shop_merchant_total_fee_calculate_type, shop_merchant_expense_category_value,
partner_merchant_total_fee_calculate_type, partner_merchant_expense_category_value,
enable_flag, submit_flag,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES {','.join(values)};
"""
if self.db.execute_update(insert_sql):
# 获取第一个插入记录的ID
first_new_id = self.db.execute_query_one("SELECT LAST_INSERT_ID();")[0]
# 为批次中的每条记录建立映射关系
for i, item in enumerate(batch):
new_id = first_new_id + i
self.id_mapper.add_mapping(table_name, item['old_id'], new_id, item['base_scene_code'], item['merchant_id'])
copy_count += 1
self.logger.info(f" 批次 {batch_num}/{total_batches} 插入完成,本批 {len(batch)} 条,累计 {copy_count} 条")
# 记录原记录映射
for record in records:
old_id = record[0]
merchant_id = record[2]
self.id_mapper.add_mapping(table_name, old_id, old_id, first_code, merchant_id)
mapping_count = self.id_mapper.get_mapping_count(table_name)
self.logger.info(f"第10步完成,共生成 {mapping_count} 条ID映射记录")
def step11_process_reconciliation_rule_group(self, merchant_id=None):
"""
第11步:处理对账分组规则表(表11)及级联处理表3和表5
dj_car_life_merchant_goods_type_group_reconciliation_rule
优化:批量插入,减少数据库交互
Args:
merchant_id: 商户ID,必须提供
"""
if merchant_id is None:
raise ValueError("step11_process_reconciliation_rule_group 必须提供 merchant_id 参数")
self.logger.info("=" * 80)
self.logger.info(f"第11步:开始处理对账分组规则表及级联表 - 商户 {merchant_id}")
# 子步骤1:处理表11(商品分组对账规则表)
self.step11_1_process_goods_type_group_reconciliation_rule(merchant_id)
# 子步骤2:处理表3(费用类目规则表,rule_type=3)
self.step11_2_process_expense_category_rule_reconciliation(merchant_id)
# 子步骤2-1:修补费用类目规则表的parent_id
self.step11_2_1_fix_expense_category_rule_parent_id(merchant_id)
# 子步骤3:处理表5(商品分组关系表,rule_type=3)
self.step11_3_process_goods_type_group_relation_reconciliation(merchant_id)
self.logger.info("第11步完成")
def step11_1_process_goods_type_group_reconciliation_rule(self, merchant_id=None):
"""
第11步-1:处理商品分组对账规则表(表11)
数据量:15,164 → 45,492(1→3)
Args:
merchant_id: 商户ID,必须提供
"""
if merchant_id is None:
raise ValueError("step11_1_process_goods_type_group_reconciliation_rule 必须提供 merchant_id 参数")
table_name = 'dj_car_life_merchant_goods_type_group_reconciliation_rule'
parent_table = 'dj_car_life_merchant_reconciliation_rule'
self.logger.info(f"第11步-1:开始处理商品分组对账规则表 - 商户 {merchant_id}")
# 1. 查询表10的映射关系
query_mapping_sql = f"""
SELECT DISTINCT old_id, new_id, base_scene_code, merchant_id
FROM tmp_rule_id_mapping
WHERE table_name = '{parent_table}'
AND old_id != new_id
AND merchant_id = {merchant_id}
ORDER BY merchant_id, old_id, new_id;
"""
mappings = self.db.execute_query(query_mapping_sql)
self.logger.info(f" 找到 {len(mappings)} 条表10的映射关系需要处理")
# 2. 收集所有需要插入的数据
insert_batch = []
for mapping in mappings:
old_reconciliation_rule_id = mapping[0]
new_reconciliation_rule_id = mapping[1]
base_scene_code = mapping[2]
merchant_id = mapping[3]
# 查询关联的表11记录
query_sql = f"""
SELECT id, rule_type, reconciliation_rule_id, group_type, goods_source
FROM {table_name}
WHERE reconciliation_rule_id = {old_reconciliation_rule_id}
ORDER BY id;
"""
records = self.db.execute_query(query_sql)
for record in records:
insert_batch.append({
'old_id': record[0],
'rule_type': record[1],
'new_reconciliation_rule_id': new_reconciliation_rule_id,
'group_type': record[3],
'goods_source': record[4],
'base_scene_code': base_scene_code,
'merchant_id': merchant_id
})
total_count = len(insert_batch)
self.logger.info(f" 收集到 {total_count} 条需要插入的记录")
if total_count == 0:
self.logger.info(f"第11步-1完成,没有需要处理的记录")
return
# 3. 批量插入(10000条/批)
batch_size = 10000
total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量插入,共 {total_batches} 个批次,每批 {batch_size} 条")
copy_count = 0
for batch_idx in range(total_batches):
start_idx = batch_idx * batch_size
end_idx = min(start_idx + batch_size, total_count)
batch = insert_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建批量插入SQL
values = []
for item in batch:
rule_type = item['rule_type']
new_reconciliation_rule_id = item['new_reconciliation_rule_id']
group_type = item['group_type']
goods_source = item['goods_source']
values.append(
f"({rule_type}, {new_reconciliation_rule_id}, {group_type}, {goods_source}, "
f"'{DATA_MIGRATION_USER}', NOW(), '{DATA_MIGRATION_USER}', NOW(), 'N')"
)
insert_sql = f"""
INSERT INTO {table_name}
(rule_type, reconciliation_rule_id, group_type, goods_source,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES {','.join(values)};
"""
if self.db.execute_update(insert_sql):
# 获取起始ID
first_new_id = self.db.execute_query_one("SELECT LAST_INSERT_ID();")[0]
# 建立映射
for i, item in enumerate(batch):
new_id = first_new_id + i
self.id_mapper.add_mapping('dj_car_life_merchant_goods_type_group_reconciliation_rule', item['old_id'], new_id, item['base_scene_code'], item['merchant_id'])
copy_count += 1
self.logger.info(f" 批次 {batch_num}/{total_batches} 插入完成,本批 {len(batch)} 条,累计 {copy_count} 条")
self.logger.info(f"第11步-1完成,共复制 {copy_count} 条记录")
def step11_2_process_expense_category_rule_reconciliation(self, merchant_id=None):
"""
第11步-2:处理费用类目规则表(对账侧,rule_type=3)
数据量:138,717 → 416,151(1→3)
Args:
merchant_id: 商户ID,必须提供
"""
if merchant_id is None:
raise ValueError("step11_2_process_expense_category_rule_reconciliation 必须提供 merchant_id 参数")
table_name = 'dj_car_life_merchant_expense_category_rule'
self.logger.info(f"第11步-2:开始处理费用类目规则表(对账侧)- 商户 {merchant_id}")
# 1. 查询表11的映射关系
query_mapping_sql = f"""
SELECT old_id, new_id, base_scene_code, merchant_id
FROM tmp_rule_id_mapping
WHERE table_name = 'dj_car_life_merchant_goods_type_group_reconciliation_rule'
AND merchant_id = {merchant_id}
ORDER BY merchant_id, old_id, base_scene_code;
"""
mappings = self.db.execute_query(query_mapping_sql)
self.logger.info(f" 找到 {len(mappings)} 条表11的映射关系需要处理")
# 2. 收集所有需要插入的数据
insert_batch = []
for mapping in mappings:
old_goods_type_group_rule_id = mapping[0]
new_goods_type_group_rule_id = mapping[1]
base_scene_code = mapping[2]
merchant_id = mapping[3]
# 查询关联的费用类目规则记录(rule_type=3)
query_sql = f"""
SELECT id, rule_type, goods_type_group_rule_id, expense_category_id, expense_category_name,
parent_expense_category_id, parent_expense_category_name, target_type, node_type,
parent_id, category_to_sort, calculate_mode, expense_category_calculate_type,
expense_category_value, target_merchant_id, target_merchant_name
FROM {table_name}
WHERE goods_type_group_rule_id = {old_goods_type_group_rule_id}
AND rule_type = 3
ORDER BY id;
"""
records = self.db.execute_query(query_sql)
for record in records:
insert_batch.append({
'old_id': record[0],
'rule_type': 3,
'new_goods_type_group_rule_id': new_goods_type_group_rule_id,
'expense_category_id': record[3],
'expense_category_name': record[4],
'parent_expense_category_id': record[5],
'parent_expense_category_name': record[6],
'target_type': record[7],
'node_type': record[8],
'parent_id': record[9],
'category_to_sort': record[10],
'calculate_mode': record[11],
'expense_category_calculate_type': record[12],
'expense_category_value': record[13],
'target_merchant_id': record[14],
'target_merchant_name': record[15],
'base_scene_code': base_scene_code,
'merchant_id': merchant_id
})
total_count = len(insert_batch)
self.logger.info(f" 收集到 {total_count} 条需要插入的记录")
if total_count == 0:
self.logger.info(f"第11步-2完成,没有需要处理的记录")
return
# 3. 批量插入(10000条/批)
batch_size = 100000
total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量插入,共 {total_batches} 个批次,每批 {batch_size} 条")
copy_count = 0
for batch_idx in range(total_batches):
start_idx = batch_idx * batch_size
end_idx = min(start_idx + batch_size, total_count)
batch = insert_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建参数化查询的值列表
values_list = []
for item in batch:
values_list.append((
3, # rule_type
item['new_goods_type_group_rule_id'],
item['expense_category_id'],
item['expense_category_name'],
item['parent_expense_category_id'],
item['parent_expense_category_name'],
item['target_type'],
item['node_type'],
item['parent_id'],
item['category_to_sort'],
item['calculate_mode'],
item['expense_category_calculate_type'],
item['expense_category_value'],
item['target_merchant_id'],
item['target_merchant_name'],
DATA_MIGRATION_USER,
DATA_MIGRATION_USER
))
insert_sql = f"""
INSERT INTO {table_name}
(rule_type, goods_type_group_rule_id, expense_category_id, expense_category_name,
parent_expense_category_id, parent_expense_category_name, target_type, node_type,
parent_id, category_to_sort, calculate_mode, expense_category_calculate_type,
expense_category_value, target_merchant_id, target_merchant_name,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), %s, NOW(), 'N')
"""
if self.db.execute_batch_insert(insert_sql, values_list):
# 获取起始ID
first_new_id = self.db.execute_query_one("SELECT LAST_INSERT_ID();")[0]
# 建立映射关系并保存到 tmp_rule_id_mapping
for i, item in enumerate(batch):
new_id = first_new_id + i
self.id_mapper.add_mapping(table_name, item['old_id'], new_id, item['base_scene_code'], item['merchant_id'])
copy_count += 1
self.logger.info(f" 批次 {batch_num}/{total_batches} 插入完成,本批 {len(batch)} 条,累计 {copy_count} 条")
self.logger.info(f"第11步-2完成,共复制 {copy_count} 条记录")
def step11_2_1_fix_expense_category_rule_parent_id(self, merchant_id=None):
"""
第11步-2-1:修补费用类目规则表的parent_id
将parent_id指向新复制的记录ID
Args:
merchant_id: 商户ID,必须提供
"""
if merchant_id is None:
raise ValueError("step11_2_1_fix_expense_category_rule_parent_id 必须提供 merchant_id 参数")
table_name = 'dj_car_life_merchant_expense_category_rule'
self.logger.info(f"第11步-2-1:开始修补费用类目规则表的parent_id - 商户 {merchant_id}")
# 执行修补SQL - 需要通过JOIN tmp_rule_id_mapping来过滤商户
fix_sql = f"""
UPDATE dj_car_life_merchant_expense_category_rule cr
INNER JOIN tmp_rule_id_mapping m ON m.table_name = '{table_name}' AND m.new_id = cr.id AND m.merchant_id = {merchant_id}
INNER JOIN
(SELECT goods_type_group_rule_id, parent_id, MIN(id) min_id
FROM (SELECT cr2.id, cr2.parent_id, cr2.goods_type_group_rule_id
FROM dj_car_life_merchant_expense_category_rule cr2
INNER JOIN tmp_rule_id_mapping m2 ON m2.table_name = '{table_name}' AND m2.new_id = cr2.id AND m2.merchant_id = {merchant_id}
WHERE cr2.created_by = 'DATA_MIGRATION'
AND cr2.parent_id IS NOT NULL
ORDER BY cr2.id ASC) tmp
GROUP BY goods_type_group_rule_id, parent_id)
t ON t.parent_id = cr.parent_id AND t.goods_type_group_rule_id = cr.goods_type_group_rule_id
SET cr.parent_id = min_id - 1
WHERE cr.created_by = 'DATA_MIGRATION';
"""
try:
# 先查询需要修补的记录数
count_sql = f"""
SELECT COUNT(*)
FROM dj_car_life_merchant_expense_category_rule cr
INNER JOIN tmp_rule_id_mapping m ON m.table_name = '{table_name}' AND m.new_id = cr.id AND m.merchant_id = {merchant_id}
INNER JOIN
(SELECT goods_type_group_rule_id, parent_id, MIN(id) min_id
FROM (SELECT cr2.id, cr2.parent_id, cr2.goods_type_group_rule_id
FROM dj_car_life_merchant_expense_category_rule cr2
INNER JOIN tmp_rule_id_mapping m2 ON m2.table_name = '{table_name}' AND m2.new_id = cr2.id AND m2.merchant_id = {merchant_id}
WHERE cr2.created_by = 'DATA_MIGRATION'
AND cr2.parent_id IS NOT NULL
ORDER BY cr2.id ASC) tmp
GROUP BY goods_type_group_rule_id, parent_id)
t ON t.parent_id = cr.parent_id AND t.goods_type_group_rule_id = cr.goods_type_group_rule_id
WHERE cr.created_by = 'DATA_MIGRATION';
"""
count_result = self.db.execute_query_one(count_sql)
affected_count = count_result[0] if count_result else 0
self.logger.info(f" 需要修补的记录数:{affected_count}")
if affected_count == 0:
self.logger.info(f"第11步-2-1完成,没有需要修补的记录")
return
# 执行修补
if self.db.execute_update(fix_sql):
self.logger.info(f"第11步-2-1完成,成功修补 {affected_count} 条记录的parent_id")
else:
self.logger.error(f"第11步-2-1失败,修补parent_id时发生错误")
except Exception as e:
self.logger.error(f"第11步-2-1执行失败:{str(e)}")
raise
def step11_3_process_goods_type_group_relation_reconciliation(self, merchant_id=None):
"""
第11步-3:处理商品分组关系表(对账侧,rule_type=3)
数据量:303,590 → 910,770(1→3)
Args:
merchant_id: 商户ID,必须提供
"""
if merchant_id is None:
raise ValueError("step11_3_process_goods_type_group_relation_reconciliation 必须提供 merchant_id 参数")
table_name = 'dj_car_life_goods_type_group_relation'
self.logger.info(f"第11步-3:开始处理商品分组关系表(对账侧)- 商户 {merchant_id}")
# 1. 查询表11的映射关系
query_mapping_sql = f"""
SELECT old_id, new_id, base_scene_code, merchant_id
FROM tmp_rule_id_mapping
WHERE table_name = 'dj_car_life_merchant_goods_type_group_reconciliation_rule'
AND merchant_id = {merchant_id}
ORDER BY merchant_id, old_id, base_scene_code;
"""
mappings = self.db.execute_query(query_mapping_sql)
self.logger.info(f" 找到 {len(mappings)} 条表11的映射关系需要处理")
# 2. 收集所有需要插入的数据
insert_batch = []
for mapping in mappings:
old_goods_type_group_rule_id = mapping[0]
new_goods_type_group_rule_id = mapping[1]
base_scene_code = mapping[2]
merchant_id = mapping[3]
# 查询关联的商品分组关系记录(rule_type=3)
query_sql = f"""
SELECT id, rule_type, goods_type_group_rule_id, category_type,
upgrade_goods_id, merchant_goods_code, goods_type, goods_type_name,
package_code, package_name
FROM {table_name}
WHERE goods_type_group_rule_id = {old_goods_type_group_rule_id}
AND rule_type = 3
ORDER BY id;
"""
records = self.db.execute_query(query_sql)
for record in records:
insert_batch.append({
'old_id': record[0],
'rule_type': 3,
'new_goods_type_group_rule_id': new_goods_type_group_rule_id,
'category_type': record[3],
'upgrade_goods_id': record[4],
'merchant_goods_code': record[5],
'goods_type': record[6],
'goods_type_name': record[7],
'package_code': record[8],
'package_name': record[9],
'base_scene_code': base_scene_code,
'merchant_id': merchant_id
})
total_count = len(insert_batch)
self.logger.info(f" 收集到 {total_count} 条需要插入的记录")
if total_count == 0:
self.logger.info(f"第11步-3完成,没有需要处理的记录")
return
# 3. 批量插入(10000条/批)
batch_size = 100000
total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量插入,共 {total_batches} 个批次,每批 {batch_size} 条")
copy_count = 0
for batch_idx in range(total_batches):
start_idx = batch_idx * batch_size
end_idx = min(start_idx + batch_size, total_count)
batch = insert_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建参数化查询的值列表
values_list = []
for item in batch:
values_list.append((
3, # rule_type
item['new_goods_type_group_rule_id'],
item['category_type'],
item['upgrade_goods_id'],
item['merchant_goods_code'],
item['goods_type'],
item['goods_type_name'],
item['package_code'],
item['package_name'],
DATA_MIGRATION_USER,
DATA_MIGRATION_USER
))
insert_sql = f"""
INSERT INTO {table_name}
(rule_type, goods_type_group_rule_id, category_type,
upgrade_goods_id, merchant_goods_code, goods_type, goods_type_name,
package_code, package_name,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), %s, NOW(), 'N')
"""
if self.db.execute_batch_insert(insert_sql, values_list):
# 注意:这里不需要建立映射,因为这些记录不会被其他表引用
copy_count += len(batch)
self.logger.info(f" 批次 {batch_num}/{total_batches} 插入完成,本批 {len(batch)} 条,累计 {copy_count} 条")
self.logger.info(f"第11步-3完成,共复制 {copy_count} 条记录")
def step12_process_rule_audit(self):
"""
第12步:处理审核记录表(表12)
dj_car_life_rule_audit
"""
self.logger.info("=" * 80)
self.logger.info("第12步:开始处理审核记录表")
table_name = 'dj_car_life_rule_audit'
# 1. 先更新原有记录的 base_scene_code(通过关联规则表获取)
self.logger.info("更新原有记录的 base_scene_code...")
self._update_audit_base_scene_code()
# 2. 处理财务审核记录(rule_type=1)
self.logger.info("处理财务审核记录(rule_type=1)...")
self._process_audit_finance()
# 3. 处理对账审核记录(rule_type=3)
self.logger.info("处理对账审核记录(rule_type=3)...")
self._process_audit_reconciliation()
mapping_count = self.id_mapper.get_mapping_count(table_name)
self.logger.info(f"第12步完成,共生成 {mapping_count} 条ID映射记录")
def _update_audit_base_scene_code(self):
"""更新审核记录表的 base_scene_code 字段"""
table_name = 'dj_car_life_rule_audit'
# 1. 更新财务审核记录(rule_type=1)- 从财务账户规则表获取 base_scene_code
self.logger.info(" 更新财务审核记录的 base_scene_code...")
update_finance_sql = f"""
UPDATE {table_name} audit
INNER JOIN dj_car_life_merchant_settle_account_rule settle
ON audit.rule_id = settle.id
SET audit.base_scene_code = settle.base_scene_code,
audit.updated_by = '{DATA_MIGRATION_USER}',
audit.updated_date = NOW()
WHERE audit.rule_type = 1
AND (audit.base_scene_code IS NULL OR audit.base_scene_code = '')
AND settle.base_scene_code IS NOT NULL
AND settle.base_scene_code != '';
"""
if self.db.execute_update(update_finance_sql):
self.logger.info(" 财务审核记录的 base_scene_code 更新完成")
# 2. 更新对账审核记录(rule_type=3)- 从对账规则表获取 base_scene_code
self.logger.info(" 更新对账审核记录的 base_scene_code...")
update_reconciliation_sql = f"""
UPDATE {table_name} audit
INNER JOIN dj_car_life_merchant_reconciliation_rule recon
ON audit.rule_id = recon.id
SET audit.base_scene_code = recon.base_scene_code,
audit.updated_by = '{DATA_MIGRATION_USER}',
audit.updated_date = NOW()
WHERE audit.rule_type = 3
AND (audit.base_scene_code IS NULL OR audit.base_scene_code = '')
AND recon.base_scene_code IS NOT NULL
AND recon.base_scene_code != '';
"""
if self.db.execute_update(update_reconciliation_sql):
self.logger.info(" 对账审核记录的 base_scene_code 更新完成")
def _process_audit_finance(self):
"""处理财务审核记录(rule_type=1)"""
table_name = 'dj_car_life_rule_audit'
settle_table = 'dj_car_life_merchant_settle_account_rule'
division_table = 'dj_car_life_merchant_division_rule'
# 从dj_car_life_rule_audit出发,查询需要拆分的旧数据
query_old_audit_sql = f"""
SELECT id, merchant_id, merchant_name, scene_type, rule_type,
rule_id, division_rule_id, effect_date_type, effect_start_date,
audit_status, audit_by, auditor_name, audit_date,
creator_name, enabled_flag, created_by, created_date, updated_by, updated_date
FROM {table_name}
WHERE scene_type = 0
AND rule_type = 1
ORDER BY id;
"""
old_audit_records = self.db.execute_query(query_old_audit_sql)
self.logger.info(f" 找到 {len(old_audit_records)} 条需要拆分的财务审核记录")
copy_count = 0
skip_count = 0
for old_record in old_audit_records:
old_id = old_record[0]
merchant_id = old_record[1]
merchant_name = old_record[2]
scene_type = old_record[3]
rule_type = old_record[4]
old_rule_id = old_record[5]
old_division_rule_id = old_record[6]
effect_date_type = old_record[7]
effect_start_date = f"'{old_record[8]}'" if old_record[8] is not None else 'NULL'
audit_status = old_record[9]
audit_by = f"'{old_record[10]}'" if old_record[10] is not None else 'NULL'
auditor_name = f"'{old_record[11]}'" if old_record[11] is not None else 'NULL'
audit_date = f"'{old_record[12]}'" if old_record[12] is not None else 'NULL'
creator_name = old_record[13]
enabled_flag = old_record[14]
created_by = old_record[15]
created_date = old_record[16]
updated_by = old_record[17]
updated_date = old_record[18]
# 查询rule_id对应的拆分后的数据
query_settle_mapping_sql = f"""
SELECT new_id, base_scene_code
FROM tmp_rule_id_mapping
WHERE table_name = '{settle_table}'
AND old_id = {old_rule_id}
ORDER BY old_id, base_scene_code;
"""
settle_mappings = self.db.execute_query(query_settle_mapping_sql)
# 查询division_rule_id对应的拆分后的数据
division_mappings = []
if old_division_rule_id is not None:
query_division_mapping_sql = f"""
SELECT new_id, base_scene_code
FROM tmp_rule_id_mapping
WHERE table_name = '{division_table}'
AND old_id = {old_division_rule_id}
ORDER BY old_id, base_scene_code;
"""
division_mappings = self.db.execute_query(query_division_mapping_sql)
# 检查两个映射列表的长度是否一致
if len(settle_mappings) == 0:
self.logger.warning(f" 审核记录 id={old_id} 的 rule_id={old_rule_id} 没有找到映射关系,跳过")
skip_count += 1
continue
if old_division_rule_id is not None and len(division_mappings) != len(settle_mappings):
self.logger.warning(f" 审核记录 id={old_id} 的 settle 和 division 映射数量不一致,跳过")
skip_count += 1
continue
# 按顺序组装新记录
# 注意:第一个场景(110101)是通过更新原记录实现的,所以只需要插入后面3个
first_scene_code = SCENE_TYPE_0_SPLIT[0] # 110101
for i in range(len(settle_mappings)):
new_settle_id = settle_mappings[i][0]
base_scene_code = settle_mappings[i][1]
# 跳过第一个场景(110101),因为它是通过更新原记录实现的
if base_scene_code == first_scene_code:
# 为原记录建立映射关系(old_id -> old_id)
self.id_mapper.add_mapping(table_name, old_id, old_id, base_scene_code)
self.logger.debug(f" 原记录映射: old_id={old_id} -> old_id={old_id}, base_scene_code={base_scene_code}")
continue
new_division_id = 'NULL'
if division_mappings and i < len(division_mappings):
new_division_id = division_mappings[i][0]
insert_sql = f"""
INSERT INTO {table_name}
(merchant_id, merchant_name, scene_type, base_scene_code, rule_type,
rule_id, division_rule_id, effect_date_type, effect_start_date,
audit_status, audit_by, auditor_name, audit_date,
creator_name, enabled_flag,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES
({merchant_id}, '{merchant_name}', {scene_type}, '{base_scene_code}', {rule_type},
{new_settle_id}, {new_division_id}, {effect_date_type}, {effect_start_date},
{audit_status}, {audit_by}, {auditor_name}, {audit_date},
'{creator_name}', '{enabled_flag}',
'{DATA_MIGRATION_USER}', NOW(), '{DATA_MIGRATION_USER}', NOW(), 'N');
"""
if self.db.execute_update(insert_sql):
new_id_sql = "SELECT LAST_INSERT_ID();"
result = self.db.execute_query_one(new_id_sql)
if result:
new_id = result[0]
self.id_mapper.add_mapping(table_name, old_id, new_id, base_scene_code)
copy_count += 1
self.logger.debug(f" 复制财务审核: old_id={old_id} -> new_id={new_id}, base_scene_code={base_scene_code}")
self.logger.info(f" 财务审核记录复制完成,共 {copy_count} 条,跳过 {skip_count} 条")
def _process_audit_reconciliation(self):
"""处理对账审核记录(rule_type=3)"""
table_name = 'dj_car_life_rule_audit'
reconciliation_table = 'dj_car_life_merchant_reconciliation_rule'
# 查询表9的映射关系
query_mapping_sql = f"""
SELECT DISTINCT old_id, new_id, base_scene_code
FROM tmp_rule_id_mapping
WHERE table_name = '{reconciliation_table}'
AND old_id != new_id
ORDER BY old_id, new_id;
"""
mappings = self.db.execute_query(query_mapping_sql)
self.logger.info(f" 找到 {len(mappings)} 条对账规则映射关系需要处理")
copy_count = 0
for mapping in mappings:
old_reconciliation_id = mapping[0]
new_reconciliation_id = mapping[1]
base_scene_code = mapping[2]
# 查询原审核记录
query_sql = f"""
SELECT id, merchant_id, merchant_name, scene_type, rule_type,
rule_id, division_rule_id, effect_date_type, effect_start_date,
audit_status, audit_by, auditor_name, audit_date,
creator_name, enabled_flag, created_by, created_date, updated_by, updated_date
FROM {table_name}
WHERE rule_type = 3
AND rule_id = {old_reconciliation_id};
"""
records = self.db.execute_query(query_sql)
for record in records:
old_id = record[0]
merchant_id = record[1]
merchant_name = record[2]
scene_type = record[3]
rule_type = record[4]
division_rule_id = record[6] if record[6] is not None else 'NULL'
effect_date_type = record[7]
effect_start_date = f"'{record[8]}'" if record[8] is not None else 'NULL'
audit_status = record[9]
audit_by = f"'{record[10]}'" if record[10] is not None else 'NULL'
auditor_name = f"'{record[11]}'" if record[11] is not None else 'NULL'
audit_date = f"'{record[12]}'" if record[12] is not None else 'NULL'
creator_name = record[13]
enabled_flag = record[14]
insert_sql = f"""
INSERT INTO {table_name}
(merchant_id, merchant_name, scene_type, base_scene_code, rule_type,
rule_id, division_rule_id, effect_date_type, effect_start_date,
audit_status, audit_by, auditor_name, audit_date,
creator_name, enabled_flag,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES
({merchant_id}, '{merchant_name}', {scene_type}, '{base_scene_code}', {rule_type},
{new_reconciliation_id}, {division_rule_id}, {effect_date_type}, {effect_start_date},
{audit_status}, {audit_by}, {auditor_name}, {audit_date},
'{creator_name}', '{enabled_flag}',
'{DATA_MIGRATION_USER}', NOW(), '{DATA_MIGRATION_USER}', NOW(), 'N');
"""
if self.db.execute_update(insert_sql):
new_id_sql = "SELECT LAST_INSERT_ID();"
result = self.db.execute_query_one(new_id_sql)
if result:
new_id = result[0]
self.id_mapper.add_mapping(table_name, old_id, new_id, base_scene_code)
copy_count += 1
self.logger.debug(f" 复制对账审核: old_id={old_id} -> new_id={new_id}")
self.logger.info(f" 对账审核记录复制完成,共 {copy_count} 条")
def step13_process_effect_record(self, merchant_id=None):
"""
第13步:处理生效记录表(表11)
dj_car_life_division_rule_effect_record
Args:
merchant_id: 商户ID,必须提供
"""
if merchant_id is None:
raise ValueError("step13_process_effect_record 必须提供 merchant_id 参数")
self.logger.info("=" * 80)
self.logger.info(f"第13步:开始处理生效记录表 - 商户 {merchant_id}")
# 子步骤 13.1:更新已存在记录的 base_scene_code
self.step13_1_update_existing_base_scene_code(merchant_id)
# 子步骤 13.2:从审核表补全生效记录(现有逻辑)注释暂不需要
# self.step13_2_sync_from_audit(merchant_id)
# 子步骤 13.3:从规则表补全未经审核的记录
self.step13_3_sync_from_rule_tables(merchant_id)
self.logger.info("=" * 80)
self.logger.info(f"第13步完成 - 商户 {merchant_id}")
def step13_1_update_existing_base_scene_code(self, merchant_id=None):
"""
子步骤 13.1:更新已存在记录的 base_scene_code
处理 base_scene_code 为空但 scene_type 有值的记录
Args:
merchant_id: 商户ID,必须提供
"""
if merchant_id is None:
raise ValueError("step13_1_update_existing_base_scene_code 必须提供 merchant_id 参数")
self.logger.info("-" * 80)
self.logger.info(f"子步骤 13.1:更新已存在记录的 base_scene_code - 商户 {merchant_id}")
table_name = 'dj_car_life_division_rule_effect_record'
# scene_type 到 base_scene_code 的映射
scene_mapping = {
0: '110101',
1: '100101',
2: '100102',
3: '100103',
7: '120101'
}
total_updated = 0
for scene_type, base_scene_code in scene_mapping.items():
update_sql = f"""
UPDATE {table_name}
SET base_scene_code = '{base_scene_code}',
updated_date = NOW()
WHERE (base_scene_code IS NULL OR base_scene_code = '')
AND scene_type = {scene_type}
AND merchant_id = {merchant_id};
"""
if self.db.execute_update(update_sql):
# 获取更新的行数
count_sql = "SELECT ROW_COUNT();"
result = self.db.execute_query_one(count_sql)
if result and result[0] > 0:
count = result[0]
total_updated += count
self.logger.info(f" scene_type={scene_type} 更新为 base_scene_code={base_scene_code},更新 {count} 条")
self.logger.info(f"子步骤 13.1 完成,共更新 {total_updated} 条记录")
def step13_2_sync_from_audit(self):
"""
子步骤 13.2:从审核表补全生效记录(现有逻辑)
"""
self.logger.info("-" * 80)
self.logger.info("子步骤 13.2:从审核表补全生效记录")
# 处理财务生效记录(rule_type=1)
self.logger.info("处理财务生效记录(rule_type=1)...")
self._process_effect_finance()
# 处理对账生效记录(rule_type=3)
self.logger.info("处理对账生效记录(rule_type=3)...")
self._process_effect_reconciliation()
self.logger.info("子步骤 13.2 完成")
def step13_3_sync_from_rule_tables(self, merchant_id=None):
"""
子步骤 13.3:从规则表补全未经审核的记录
处理 rule_audit_id 为 NULL 的生效记录
Args:
merchant_id: 商户ID,必须提供
"""
if merchant_id is None:
raise ValueError("step13_3_sync_from_rule_tables 必须提供 merchant_id 参数")
self.logger.info("-" * 80)
self.logger.info(f"子步骤 13.3:从规则表补全未经审核的记录 - 商户 {merchant_id}")
# 处理财务分账规则
self._sync_settle_and_division_rules(merchant_id)
# 处理对账规则
self._sync_reconciliation_rules(merchant_id)
self.logger.info(f"子步骤 13.3 完成 - 商户 {merchant_id}")
def _sync_settle_and_division_rules(self, merchant_id=None):
"""
补全财务分账规则的生效记录
根据 dj_car_life_merchant_settle_account_rule 和 dj_car_life_merchant_division_rule
Args:
merchant_id: 商户ID,必须提供
"""
if merchant_id is None:
raise ValueError("_sync_settle_and_division_rules 必须提供 merchant_id 参数")
self.logger.info(f"处理财务分账规则 - 商户 {merchant_id}...")
table_name = 'dj_car_life_division_rule_effect_record'
settle_table = 'dj_car_life_merchant_settle_account_rule'
division_table = 'dj_car_life_merchant_division_rule'
# 1. 获取所有需要处理的旧财务规则ID(按商户过滤)
query_old_ids_sql = f"""
SELECT DISTINCT old_id
FROM tmp_rule_id_mapping
WHERE table_name = '{settle_table}'
AND merchant_id = {merchant_id}
ORDER BY old_id;
"""
old_ids = self.db.execute_query(query_old_ids_sql)
self.logger.info(f" 查询到旧财务规则ID数量:{len(old_ids)} 个")
insert_count = 0
skip_count = 0
error_count = 0
for old_id_tuple in old_ids:
old_settle_rule_id = old_id_tuple[0]
# 2. 查询该旧规则ID对应的最新生效记录(去重)
query_effect_sql = f"""
SELECT id,merchant_id,merchant_name,rule_type,scene_type,base_scene_code,rule_id,division_rule_id,effect_start_date,effect_end_date
FROM {table_name}
WHERE rule_id = {old_settle_rule_id}
AND rule_type = 1
ORDER BY updated_date DESC, created_date DESC
LIMIT 1;
"""
old_effect_record = self.db.execute_query_one(query_effect_sql)
if not old_effect_record:
self.logger.debug(f" 旧规则ID {old_settle_rule_id} 没有找到对应的生效记录,跳过")
continue
# 解析旧生效记录
old_effect_id = old_effect_record[0]
merchant_id = old_effect_record[1]
merchant_name = old_effect_record[2]
rule_type = old_effect_record[3]
scene_type = old_effect_record[4]
old_division_rule_id = old_effect_record[7]
effect_start_date = old_effect_record[8]
effect_end_date = old_effect_record[9]
# 3. 查询财务规则拆分后的新ID列表
query_new_settle_sql = f"""
SELECT new_id, base_scene_code
FROM tmp_rule_id_mapping
WHERE table_name = '{settle_table}'
AND old_id = {old_settle_rule_id}
ORDER BY old_id, new_id;
"""
new_settle_rules = self.db.execute_query(query_new_settle_sql)
if not new_settle_rules:
self.logger.warning(f" 旧财务规则ID {old_settle_rule_id} 没有找到拆分后的新ID,跳过")
error_count += 1
continue
# 4. 查询分账规则拆分后的新ID列表(如果有)
new_division_rules = []
if old_division_rule_id is not None:
query_new_division_sql = f"""
SELECT new_id, base_scene_code
FROM tmp_rule_id_mapping
WHERE table_name = '{division_table}'
AND old_id = {old_division_rule_id}
ORDER BY old_id, new_id;
"""
new_division_rules = self.db.execute_query(query_new_division_sql)
# 检查数量是否一致
if len(new_settle_rules) != len(new_division_rules):
self.logger.error(f" 财务规则和分账规则拆分数量不一致: settle={len(new_settle_rules)}, division={len(new_division_rules)}")
error_count += 1
continue
# 5. 按顺序一一对应组装新记录
for i in range(len(new_settle_rules)):
new_settle_rule_id = new_settle_rules[i][0]
base_scene_code = new_settle_rules[i][1]
new_division_rule_id = None
if new_division_rules and i < len(new_division_rules):
new_division_rule_id = new_division_rules[i][0]
# 6. 幂等性检查:是否已存在
if new_division_rule_id is not None:
div_condition = f"AND division_rule_id = {new_division_rule_id}"
else:
div_condition = "AND division_rule_id IS NULL"
check_exist_sql = f"""
SELECT COUNT(*) FROM {table_name}
WHERE rule_id = {new_settle_rule_id}
AND rule_type = 1
AND merchant_id = {merchant_id}
{div_condition};
"""
result = self.db.execute_query_one(check_exist_sql)
if result and result[0] > 0:
self.logger.debug(f" 记录已存在,跳过: rule_id={new_settle_rule_id}, base_scene_code={base_scene_code}")
skip_count += 1
continue
# 7. 组装新记录(处理 None 转 NULL)
effect_start_date_str = f"'{effect_start_date}'" if effect_start_date is not None else 'NULL'
effect_end_date_str = f"'{effect_end_date}'" if effect_end_date is not None else 'NULL'
new_division_rule_id_str = str(new_division_rule_id) if new_division_rule_id is not None else 'NULL'
base_scene_code_str = f"'{base_scene_code}'" if base_scene_code is not None else 'NULL'
# 8. 插入新记录
insert_sql = f"""
INSERT INTO {table_name}
(merchant_id, merchant_name, rule_type, scene_type, base_scene_code,
rule_id, division_rule_id, effect_start_date, effect_end_date,
rule_audit_id,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES
({merchant_id}, '{merchant_name}', {rule_type}, {scene_type}, {base_scene_code_str},
{new_settle_rule_id}, {new_division_rule_id_str}, {effect_start_date_str}, {effect_end_date_str},
NULL,
'{DATA_MIGRATION_USER}', NOW(), '{DATA_MIGRATION_USER}', NOW(), 'N');
"""
if self.db.execute_update(insert_sql):
# 获取新插入的ID
new_id_sql = "SELECT LAST_INSERT_ID();"
result = self.db.execute_query_one(new_id_sql)
if result:
new_id = result[0]
# 保存ID映射关系
self.id_mapper.add_mapping(table_name, old_effect_id, new_id, base_scene_code, merchant_id)
insert_count += 1
self.logger.debug(f" 插入新记录: old_id={old_effect_id} -> new_id={new_id}, rule_id={new_settle_rule_id}, division_rule_id={new_division_rule_id_str}, base_scene_code={base_scene_code}")
else:
error_count += 1
self.logger.error(f" 获取新ID失败: rule_id={new_settle_rule_id}")
else:
error_count += 1
self.logger.error(f" 插入失败: rule_id={new_settle_rule_id}")
self.logger.info(f" 财务分账规则处理完成,共插入:{insert_count} 条新记录,跳过:{skip_count} 条,错误:{error_count} 条")
def _sync_reconciliation_rules(self, merchant_id=None):
"""
补全对账规则的生效记录
根据 dj_car_life_merchant_reconciliation_rule
Args:
merchant_id: 商户ID,必须提供
"""
if merchant_id is None:
raise ValueError("_sync_reconciliation_rules 必须提供 merchant_id 参数")
self.logger.info(f"处理对账规则 - 商户 {merchant_id}...")
table_name = 'dj_car_life_division_rule_effect_record'
reconciliation_table = 'dj_car_life_merchant_reconciliation_rule'
# 1. 获取所有需要处理的旧对账规则ID(按商户过滤)
query_old_ids_sql = f"""
SELECT DISTINCT old_id
FROM tmp_rule_id_mapping
WHERE table_name = '{reconciliation_table}'
AND merchant_id = {merchant_id}
ORDER BY old_id;
"""
old_ids = self.db.execute_query(query_old_ids_sql)
self.logger.info(f" 查询到旧对账规则ID数量:{len(old_ids)} 个")
insert_count = 0
skip_count = 0
error_count = 0
for old_id_tuple in old_ids:
old_reconciliation_rule_id = old_id_tuple[0]
# 2. 查询该旧规则ID对应的最新生效记录(去重)
query_effect_sql = f"""
SELECT id,merchant_id,merchant_name,rule_type,scene_type,base_scene_code,rule_id,division_rule_id,effect_start_date,effect_end_date
FROM {table_name}
WHERE rule_id = {old_reconciliation_rule_id}
AND rule_type = 3
ORDER BY updated_date DESC, created_date DESC
LIMIT 1;
"""
old_effect_record = self.db.execute_query_one(query_effect_sql)
if not old_effect_record:
self.logger.debug(f" 旧规则ID {old_reconciliation_rule_id} 没有找到对应的生效记录,跳过")
continue
# 解析旧生效记录
old_effect_id = old_effect_record[0]
merchant_id = old_effect_record[1]
merchant_name = old_effect_record[2]
rule_type = old_effect_record[3]
scene_type = old_effect_record[4]
effect_start_date = old_effect_record[8]
effect_end_date = old_effect_record[9]
# 3. 查询对账规则拆分后的新ID列表
query_new_reconciliation_sql = f"""
SELECT new_id, base_scene_code
FROM tmp_rule_id_mapping
WHERE table_name = '{reconciliation_table}'
AND old_id = {old_reconciliation_rule_id}
ORDER BY old_id, new_id;
"""
new_reconciliation_rules = self.db.execute_query(query_new_reconciliation_sql)
if not new_reconciliation_rules:
self.logger.warning(f" 旧对账规则ID {old_reconciliation_rule_id} 没有找到拆分后的新ID,跳过")
error_count += 1
continue
# 4. 为每个新ID生成一条记录
for new_rule_tuple in new_reconciliation_rules:
new_reconciliation_rule_id = new_rule_tuple[0]
base_scene_code = new_rule_tuple[1]
# 5. 幂等性检查:是否已存在
check_exist_sql = f"""
SELECT COUNT(*) FROM {table_name}
WHERE rule_id = {new_reconciliation_rule_id}
AND rule_type = 3
AND merchant_id = {merchant_id};
"""
result = self.db.execute_query_one(check_exist_sql)
if result and result[0] > 0:
self.logger.debug(f" 记录已存在,跳过: rule_id={new_reconciliation_rule_id}, base_scene_code={base_scene_code}")
skip_count += 1
continue
# 6. 组装新记录(处理 None 转 NULL)
effect_start_date_str = f"'{effect_start_date}'" if effect_start_date is not None else 'NULL'
effect_end_date_str = f"'{effect_end_date}'" if effect_end_date is not None else 'NULL'
base_scene_code_str = f"'{base_scene_code}'" if base_scene_code is not None else 'NULL'
# 7. 插入新记录(division_rule_id 为 NULL)
insert_sql = f"""
INSERT INTO {table_name}
(merchant_id, merchant_name, rule_type, scene_type, base_scene_code,
rule_id, division_rule_id, effect_start_date, effect_end_date,
rule_audit_id,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES
({merchant_id}, '{merchant_name}', {rule_type}, {scene_type}, {base_scene_code_str},
{new_reconciliation_rule_id}, NULL, {effect_start_date_str}, {effect_end_date_str},
NULL,
'{DATA_MIGRATION_USER}', NOW(), '{DATA_MIGRATION_USER}', NOW(), 'N');
"""
if self.db.execute_update(insert_sql):
# 获取新插入的ID
new_id_sql = "SELECT LAST_INSERT_ID();"
result = self.db.execute_query_one(new_id_sql)
if result:
new_id = result[0]
# 保存ID映射关系
self.id_mapper.add_mapping(table_name, old_effect_id, new_id, base_scene_code, merchant_id)
insert_count += 1
self.logger.debug(f" 插入新记录: old_id={old_effect_id} -> new_id={new_id}, rule_id={new_reconciliation_rule_id}, base_scene_code={base_scene_code}")
else:
error_count += 1
self.logger.error(f" 获取新ID失败: rule_id={new_reconciliation_rule_id}")
else:
error_count += 1
self.logger.error(f" 插入失败: rule_id={new_reconciliation_rule_id}")
self.logger.info(f" 对账规则处理完成,共插入:{insert_count} 条新记录,跳过:{skip_count} 条,错误:{error_count} 条")
def _process_effect_finance(self):
"""处理财务生效记录(rule_type=1)- 批量优化版本"""
table_name = 'dj_car_life_division_rule_effect_record'
audit_table = 'dj_car_life_rule_audit'
# 查询表12(财务审核)的映射关系
query_mapping_sql = f"""
SELECT DISTINCT m.old_id, m.new_id, m.base_scene_code
FROM tmp_rule_id_mapping m
JOIN {audit_table} ra ON ra.id = m.new_id AND ra.rule_type = 1
WHERE m.table_name = '{audit_table}'
AND m.old_id != m.new_id
ORDER BY m.old_id, m.new_id;
"""
mappings = self.db.execute_query(query_mapping_sql)
self.logger.info(f" 找到 {len(mappings)} 条审核记录映射关系需要处理")
# 第一阶段:收集所有需要插入的数据
insert_batch = []
skip_count = 0
error_count = 0
for mapping in mappings:
old_audit_id = mapping[0]
new_audit_id = mapping[1]
base_scene_code = mapping[2]
# 查询新审核记录的关联信息
audit_query = f"""
SELECT rule_id, division_rule_id, merchant_id, merchant_name, scene_type, rule_type
FROM {audit_table}
WHERE id = {new_audit_id};
"""
audit_record = self.db.execute_query_one(audit_query)
if not audit_record:
self.logger.warning(f" 未找到新审核记录: new_audit_id={new_audit_id}")
error_count += 1
continue
new_rule_id = audit_record[0]
new_division_rule_id = audit_record[1]
merchant_id = audit_record[2]
merchant_name = audit_record[3]
scene_type = audit_record[4]
rule_type = audit_record[5]
# 先查询旧审核记录的 rule_id
old_rule_query = f"""
SELECT rule_id
FROM {audit_table}
WHERE id = {old_audit_id};
"""
old_rule_record = self.db.execute_query_one(old_rule_query)
if not old_rule_record:
self.logger.warning(f" 未找到旧审核记录: old_audit_id={old_audit_id}")
error_count += 1
continue
old_rule_id = old_rule_record[0]
# 查询原生效记录(使用旧审核记录的 rule_id)
query_sql = f"""
SELECT id, merchant_id, merchant_name, rule_type, scene_type,
rule_id, division_rule_id, effect_start_date, effect_end_date,
rule_audit_id, created_by, created_date, updated_by, updated_date
FROM {table_name}
WHERE rule_audit_id = {old_audit_id} AND rule_id = {old_rule_id}
limit 1;
"""
records = self.db.execute_query(query_sql)
for record in records:
old_id = record[0]
effect_start_date = record[7]
effect_end_date = record[8]
# 幂等性检查:判断是否已存在相同的记录
if new_division_rule_id is not None:
div_condition = f"division_rule_id = {new_division_rule_id}"
else:
div_condition = "division_rule_id IS NULL"
check_exist_sql = f"""
SELECT id FROM {table_name}
WHERE rule_audit_id = {new_audit_id}
AND rule_id = {new_rule_id}
AND {div_condition}
AND base_scene_code = '{base_scene_code}'
LIMIT 1;
"""
exist_record = self.db.execute_query_one(check_exist_sql)
if exist_record:
existing_id = exist_record[0]
self.logger.debug(f" 记录已存在,跳过: rule_audit_id={new_audit_id}, existing_id={existing_id}")
# 记录映射关系(如果还没记录)
self.id_mapper.add_mapping(table_name, old_id, existing_id, base_scene_code)
skip_count += 1
continue
# 收集待插入数据
insert_batch.append({
'old_id': old_id,
'merchant_id': merchant_id,
'merchant_name': merchant_name,
'rule_type': rule_type,
'scene_type': scene_type,
'base_scene_code': base_scene_code,
'new_rule_id': new_rule_id,
'new_division_rule_id': new_division_rule_id,
'effect_start_date': effect_start_date,
'effect_end_date': effect_end_date,
'new_audit_id': new_audit_id
})
total_count = len(insert_batch)
self.logger.info(f" 收集到 {total_count} 条需要插入的记录")
if total_count == 0:
self.logger.info(f" 财务生效记录处理完成: 新增 0 条, 跳过 {skip_count} 条, 错误 {error_count} 条")
return
# 第二阶段:批量插入
batch_size = 10000
total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量插入,共 {total_batches} 个批次,每批 {batch_size} 条")
copy_count = 0
for batch_idx in range(total_batches):
start_idx = batch_idx * batch_size
end_idx = min(start_idx + batch_size, total_count)
batch = insert_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建批量插入SQL
values = []
for item in batch:
merchant_id = item['merchant_id']
merchant_name = item['merchant_name']
rule_type = item['rule_type']
scene_type = item['scene_type']
base_scene_code = item['base_scene_code']
new_rule_id = item['new_rule_id']
new_division_rule_id = item['new_division_rule_id'] if item['new_division_rule_id'] is not None else 'NULL'
effect_start_date = f"'{item['effect_start_date']}'" if item['effect_start_date'] is not None else 'NULL'
effect_end_date = f"'{item['effect_end_date']}'" if item['effect_end_date'] is not None else 'NULL'
new_audit_id = item['new_audit_id']
values.append(
f"({merchant_id}, '{merchant_name}', {rule_type}, {scene_type}, '{base_scene_code}', "
f"{new_rule_id}, {new_division_rule_id}, {effect_start_date}, {effect_end_date}, "
f"{new_audit_id}, "
f"'{DATA_MIGRATION_USER}', NOW(), '{DATA_MIGRATION_USER}', NOW(), 'N')"
)
insert_sql = f"""
INSERT INTO {table_name}
(merchant_id, merchant_name, rule_type, scene_type, base_scene_code,
rule_id, division_rule_id, effect_start_date, effect_end_date,
rule_audit_id,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES {','.join(values)};
"""
if self.db.execute_update(insert_sql):
# 获取第一个插入记录的ID
first_new_id = self.db.execute_query_one("SELECT LAST_INSERT_ID();")[0]
# 为批次中的每条记录建立映射关系
for i, item in enumerate(batch):
new_id = first_new_id + i
self.id_mapper.add_mapping(table_name, item['old_id'], new_id, item['base_scene_code'])
copy_count += 1
self.logger.info(f" 批次 {batch_num}/{total_batches} 插入完成,本批 {len(batch)} 条,累计 {copy_count} 条")
self.logger.info(f" 财务生效记录处理完成: 新增 {copy_count} 条, 跳过 {skip_count} 条, 错误 {error_count} 条")
def _process_effect_reconciliation(self):
"""处理对账生效记录(rule_type=3)"""
table_name = 'dj_car_life_division_rule_effect_record'
audit_table = 'dj_car_life_rule_audit'
# 查询表12(对账审核)的映射关系
query_mapping_sql = f"""
SELECT DISTINCT m.old_id, m.new_id, m.base_scene_code
FROM tmp_rule_id_mapping m
JOIN {audit_table} ra ON ra.id = m.new_id AND ra.rule_type = 3
WHERE m.table_name = '{audit_table}'
AND m.old_id != m.new_id
ORDER BY m.old_id, m.new_id;
"""
def _process_effect_reconciliation(self):
"""处理对账生效记录(rule_type=3)- 批量优化版本"""
table_name = 'dj_car_life_division_rule_effect_record'
audit_table = 'dj_car_life_rule_audit'
# 查询表12(对账审核)的映射关系
query_mapping_sql = f"""
SELECT DISTINCT m.old_id, m.new_id, m.base_scene_code
FROM tmp_rule_id_mapping m
JOIN {audit_table} ra ON ra.id = m.new_id AND ra.rule_type = 3
WHERE m.table_name = '{audit_table}'
AND m.old_id != m.new_id
ORDER BY m.old_id, m.new_id;
"""
mappings = self.db.execute_query(query_mapping_sql)
self.logger.info(f" 找到 {len(mappings)} 条对账审核映射关系需要处理")
# 第一阶段:收集所有需要插入的数据
insert_batch = []
skip_count = 0
error_count = 0
for mapping in mappings:
old_audit_id = mapping[0]
new_audit_id = mapping[1]
base_scene_code = mapping[2]
# 查询新审核记录的关联信息
audit_query = f"""
SELECT rule_id, division_rule_id, merchant_id, merchant_name, scene_type, rule_type
FROM {audit_table}
WHERE id = {new_audit_id} ;
"""
audit_record = self.db.execute_query_one(audit_query)
if not audit_record:
self.logger.warning(f" 未找到新审核记录: new_audit_id={new_audit_id}")
error_count += 1
continue
new_rule_id = audit_record[0]
division_rule_id = audit_record[1]
merchant_id = audit_record[2]
merchant_name = audit_record[3]
scene_type = audit_record[4]
rule_type = audit_record[5]
# 先查询旧审核记录的 rule_id
old_rule_query = f"""
SELECT rule_id
FROM {audit_table}
WHERE id = {old_audit_id} ;
"""
old_rule_record = self.db.execute_query_one(old_rule_query)
if not old_rule_record:
self.logger.warning(f" 未找到旧审核记录: old_audit_id={old_audit_id}")
error_count += 1
continue
old_rule_id = old_rule_record[0]
# 查询原生效记录(使用旧审核记录的 rule_id)
query_sql = f"""
SELECT id, merchant_id, merchant_name, rule_type, scene_type,
rule_id, division_rule_id, effect_start_date, effect_end_date,
rule_audit_id, created_by, created_date, updated_by, updated_date
FROM {table_name}
WHERE rule_audit_id = {old_audit_id} AND rule_id = {old_rule_id}
limit 1;
"""
records = self.db.execute_query(query_sql)
for record in records:
old_id = record[0]
effect_start_date = record[7]
effect_end_date = record[8]
# 幂等性检查:判断是否已存在相同的记录
if division_rule_id is not None:
div_condition = f"division_rule_id = {division_rule_id}"
else:
div_condition = "division_rule_id IS NULL"
check_exist_sql = f"""
SELECT id FROM {table_name}
WHERE rule_audit_id = {new_audit_id}
AND rule_id = {new_rule_id}
AND {div_condition}
AND base_scene_code = '{base_scene_code}'
LIMIT 1;
"""
exist_record = self.db.execute_query_one(check_exist_sql)
if exist_record:
existing_id = exist_record[0]
self.logger.debug(f" 记录已存在,跳过: rule_audit_id={new_audit_id}, existing_id={existing_id}")
# 记录映射关系(如果还没记录)
self.id_mapper.add_mapping(table_name, old_id, existing_id, base_scene_code)
skip_count += 1
continue
# 收集待插入数据
insert_batch.append({
'old_id': old_id,
'merchant_id': merchant_id,
'merchant_name': merchant_name,
'rule_type': rule_type,
'scene_type': scene_type,
'base_scene_code': base_scene_code,
'new_rule_id': new_rule_id,
'division_rule_id': division_rule_id,
'effect_start_date': effect_start_date,
'effect_end_date': effect_end_date,
'new_audit_id': new_audit_id
})
total_count = len(insert_batch)
self.logger.info(f" 收集到 {total_count} 条需要插入的记录")
if total_count == 0:
self.logger.info(f" 对账生效记录处理完成: 新增 0 条, 跳过 {skip_count} 条, 错误 {error_count} 条")
return
# 第二阶段:批量插入
batch_size = 10000
total_batches = (total_count + batch_size - 1) // batch_size
self.logger.info(f" 开始批量插入,共 {total_batches} 个批次,每批 {batch_size} 条")
copy_count = 0
for batch_idx in range(total_batches):
start_idx = batch_idx * batch_size
end_idx = min(start_idx + batch_size, total_count)
batch = insert_batch[start_idx:end_idx]
batch_num = batch_idx + 1
# 构建批量插入SQL
values = []
for item in batch:
merchant_id = item['merchant_id']
merchant_name = item['merchant_name']
rule_type = item['rule_type']
scene_type = item['scene_type']
base_scene_code = item['base_scene_code']
new_rule_id = item['new_rule_id']
division_rule_id = item['division_rule_id'] if item['division_rule_id'] is not None else 'NULL'
effect_start_date = f"'{item['effect_start_date']}'" if item['effect_start_date'] is not None else 'NULL'
effect_end_date = f"'{item['effect_end_date']}'" if item['effect_end_date'] is not None else 'NULL'
new_audit_id = item['new_audit_id']
values.append(
f"({merchant_id}, '{merchant_name}', {rule_type}, {scene_type}, '{base_scene_code}', "
f"{new_rule_id}, {division_rule_id}, {effect_start_date}, {effect_end_date}, "
f"{new_audit_id}, "
f"'{DATA_MIGRATION_USER}', NOW(), '{DATA_MIGRATION_USER}', NOW(), 'N')"
)
insert_sql = f"""
INSERT INTO {table_name}
(merchant_id, merchant_name, rule_type, scene_type, base_scene_code,
rule_id, division_rule_id, effect_start_date, effect_end_date,
rule_audit_id,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES {','.join(values)};
"""
if self.db.execute_update(insert_sql):
# 获取第一个插入记录的ID
first_new_id = self.db.execute_query_one("SELECT LAST_INSERT_ID();")[0]
# 为批次中的每条记录建立映射关系
for i, item in enumerate(batch):
new_id = first_new_id + i
self.id_mapper.add_mapping(table_name, item['old_id'], new_id, item['base_scene_code'])
copy_count += 1
self.logger.info(f" 批次 {batch_num}/{total_batches} 插入完成,本批 {len(batch)} 条,累计 {copy_count} 条")
self.logger.info(f" 对账生效记录处理完成: 新增 {copy_count} 条, 跳过 {skip_count} 条, 错误 {error_count} 条")